Class: JsonApiServer::Fields

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

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, **_options)
  @request = request
  @params = request.query_parameters
end

Instance Attribute Details

#paramsObject (readonly)

Query parameters from #request.



46
47
48
# File 'lib/json_api_server/fields.rb', line 46

def params
  @params
end

#requestObject (readonly)

Controller request object.



43
44
45
# File 'lib/json_api_server/fields.rb', line 43

def request
  @request
end

Instance Method Details

#sparse_fieldsObject

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