On Monday, May 18, 2020 at 6:49:26 AM UTC-7, Robby wrote:
>
> Hi Jeremy,
>
> What would you suggest is the best method to only select a set of
> predefined "*public*" columns for API purposes? Currently, I have a
> PUBLIC_COLUMNS constant defined inside the User model and am doing the
> following for GET/POST request for */api/v1/users *endpoint. Is there
> some sort of a scope I can define inside the model that would work for both
> multiple and single resource requests?
>
>
> class User < Sequel::Model
> PUBLIC_COLUMNS = %i{id name email phone timezone created_at updated_at}
>
>
dataset_module do
select :public_columns, *PUBLIC_COLUMNS
end
end
>
> class App
> hash_branch(:api_v1, 'users') do |r|
> r.is do
> r.get do
> @users = User.select(User::PUBLIC_COLUMNS)
>
>
@users = User.public_columns.all
> { status: 200, data: @users }
> end
>
> r.post do
> @user = User.new(user_params)
>
> if @user.valid?
> @user.save; @user.columns.delete_if { |k|
> !User::PUBLIC_COLUMNS.include?(k) }
>
>
You could reuse public_columns here, but it would cause another query.
Your approach is faster.
> { status: 200, data: @user }
> else
> { status: 422, data: @user.errors }
> end
> end
> end
> end
>
> def user_params
> typecast_params.convert!(symbolize: true) do |tp|
> tp.str([:name, :email, :phone, :timezone])
> end.delete_if { |k, v| v.nil? }
> end
> end
>
>
Another approach would be making the User dataset only select the public
columns by default:
self.dataset = dataset.select(*PUBLIC_COLUMNS)
Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sequel-talk/ba38b08d-a752-4eff-812d-40aa54ce5ae2%40googlegroups.com.