Class: JsonApiServer::Fields
- Inherits:
-
Object
- Object
- JsonApiServer::Fields
- Defined in:
- lib/json_api_server/fields.rb
Overview
Description:
Implements sparse fieldsets per JSON API spec jsonapi.org/format/#fetching-sparse-fieldsets. Spec states: “A client MAY request that an endpoint return only specific fields in the response on a per-type basis by including a fields parameter.”
This class extracts sparse fields and organizes them by ‘type’ which is associated with a a serializer. There is no whitelisting. It’s assumed the serializer or view controls which fields to return.
Usage:
A sparse fields request look like:
/articles?include=author&fields[articles]=title,body,author&fields[people]=name
This is converted to a hash:
{
'articles' => ['title', 'body', 'author'],
'people' => ['name']
}
Examples:
Given request: articles?include=author&fields[articles]=title,body,author&fields[people]=name
req = JsonApiServer::Fields.new(request)
req.sparse_fields # => {'articles => ['title', 'body', 'author'], 'people' => ['name']}
Given request: /articles
req = JsonApiServer::Fields.new(request)
req.sparse_fields # => nil
Note:
-
JsonApiServer::AttributesBuilder provides methods for using this class in serializers or views.
-
JsonApiServer::Builder class provides an easier way to use this class.
Instance Attribute Summary collapse
-
#params ⇒ Object
readonly
Query parameters from #request.
-
#request ⇒ Object
readonly
Controller request object.
Instance Method Summary collapse
-
#initialize(request, **_options) ⇒ Fields
constructor
Arguments:.
-
#sparse_fields ⇒ Object
nil when there are no sparse fields in the request.
Constructor Details
#initialize(request, **_options) ⇒ Fields
Arguments:
-
request
- ActionDispatch::Request object. -
options
(Hash) - Reserved but not used.
52 53 54 55 |
# File 'lib/json_api_server/fields.rb', line 52 def initialize(request, **) @request = request @params = request.query_parameters end |
Instance Attribute Details
#params ⇒ Object (readonly)
Query parameters from #request.
46 47 48 |
# File 'lib/json_api_server/fields.rb', line 46 def params @params end |
#request ⇒ Object (readonly)
Controller request object.
43 44 45 |
# File 'lib/json_api_server/fields.rb', line 43 def request @request end |
Instance Method Details
#sparse_fields ⇒ Object
nil when there are no sparse fields in the request. Otherwise, returns a hash of format:
{'<type>' => ['<field name 1>', '<field name 2>', ... ], ...}.
60 61 62 63 64 65 66 67 68 |
# File 'lib/json_api_server/fields.rb', line 60 def sparse_fields @sparse_fields ||= begin return nil unless @params[:fields].respond_to?(:key) hash = @params[:fields].each_with_object({}) do |(k, v), sum| sum[k.to_s] = convert(v) if v.present? && v.respond_to?(:split) end hash.any? ? hash : nil end end |