Open
Description
In Grape Entity there is the only
method that lets you declare what attributes you want in your response
This is hardcoded by the endpoint and it is not configured by the client.
Bundle::Entity.represent( @bundle, only: [:id, jobs: [:id, country: :id]] )
What if the client asks what attributes he needs in his response?
Pass the attributes you need in your response as parameters and get back only what you need so you have an graphql like
support with the minimum effort!
How this can be done?
- In each
Grape::Formatter
select only the__only__
attributes
Why you dont pass the __only__
to Entity's only
?
- Because you are limited only when you use an Entity and most of endpoinds can return a hash, array etc
This is just a food for thought and I would like to know what the pros and cons of this implementation
An Implementation Example:
module Grape
module Formatter
module Json
class << self
def call(object, _env)
only = _env[Grape::Env::RACK_REQUEST_QUERY_HASH]["__only__"]
if object.respond_to?(:to_json)
return only.present? ? object.to_json(only: only) : object.to_json
end
MultiJson.dump(object)
end
end
end
end
end
Create params from a hash:
[:id, jobs: [:id, country: :id]].to_query('__only__')
It will generate:
#=> "__only__%5B%5D=id&__only__%5B%5D%5Bjobs%5D%5B%5D=id&__only__%5B%5D%5Bjobs%5D%5B%5D%5Bcountry%5D=id"
Request with the __only__
params
Get back only the attributes you need
{
"id": 68,
"jobs": [
{ "id": 11743,
"country": { "id": 1} }
]
}