class JsonApiServer::Fields

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:

Attributes

params[R]

Query parameters from request.

request[R]

Controller request object.

Public Class Methods

new(request, **_options) click to toggle source

Arguments:

  • request - ActionDispatch::Request object.

  • options (Hash) - Reserved but not used.

# File lib/json_api_server/fields.rb, line 52
def initialize(request, **_options)
  @request = request
  @params = request.query_parameters
end

Public Instance Methods

sparse_fields() click to toggle source

nil when there are no sparse fields in the request. Otherwise, returns a hash of format:

{'<type>' => ['<field name 1>', '<field name 2>', ... ], ...}.
# 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

Protected Instance Methods

convert(string) click to toggle source
# File lib/json_api_server/fields.rb, line 72
def convert(string)
  string.split(',').map!(&:strip)
end