Skip to content

Instantly share code, notes, and snippets.

@Bajena
Last active October 11, 2019 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bajena/ba05f88c54eac91ae49eaa5566f372cd to your computer and use it in GitHub Desktop.
Save Bajena/ba05f88c54eac91ae49eaa5566f372cd to your computer and use it in GitHub Desktop.
Using sparse fieldsets in ActiveModelSerializers
class BaseApiController
def render_json_api(options)
render(
options.merge(included).merge(fields: fields).merge(adapter: :json_api)
)
end
# Allows limiting fields in given resource type's payloads.
# `fields` param is sent as a hash in which:
# - keys are singular or plural resource names (e.g. `accounts` or `account`)
# - values are attribute names in snake or camel case.
# Can be either sent as array:
# `fields[accounts][]=name&fields[accounts][]=search_interval`
# or divided by commas: `fields[accounts]=name,searchInterval`
#
# Examples of valid request:
# - /accounts/1?fields[account]=name,search_interval&fields[custom_feeds]=notifications&include[]=custom_feeds
# - /accounts/1?fields[account][]=searchInterval&fields[account][]=name&fields[custom_feeds][]=notifications&include[]=custom_feeds
#
# More info: https://jsonapi.org/format/#fetching-sparse-fieldsets
def fields
result = params.permit(fields: {})[:fields]
return unless result.respond_to?(:to_h)
result.to_h.map do |k, v|
v = v.split(",") if v.is_a?(String)
[k, v.map(&:underscore)]
end.to_h
end
def included
params.permit(include: []).to_h.symbolize_keys
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment