Module: ActiveModelSerializers::Jsonapi

Defined in:
lib/active_model_serializers/register_jsonapi_renderer.rb

Defined Under Namespace

Modules: ControllerSupport

Constant Summary collapse

MEDIA_TYPE =
'application/vnd.api+json'.freeze
HEADERS =
{
  response: { 'CONTENT_TYPE'.freeze => MEDIA_TYPE },
  request:  { 'ACCEPT'.freeze => MEDIA_TYPE }
}.freeze

Class Method Summary collapse

Class Method Details

.installObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/active_model_serializers/register_jsonapi_renderer.rb', line 35

def self.install
  # actionpack/lib/action_dispatch/http/mime_types.rb
  Mime::Type.register MEDIA_TYPE, :jsonapi

  if Rails::VERSION::MAJOR >= 5
    ActionDispatch::Request.parameter_parsers[:jsonapi] = parser
  else
    ActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime[:jsonapi]] = parser
  end

  # ref https://github.com/rails/rails/pull/21496
  ActionController::Renderers.add :jsonapi do |json, options|
    json = serialize_jsonapi(json, options).to_json(options) unless json.is_a?(String)
    self.content_type ||= Mime[:jsonapi]
    self.response_body = json
  end
end

.parserObject

Proposal: should actually deserialize the JSON API params to the hash format expected by ‘ActiveModel::Serializers::JSON` actionpack/lib/action_dispatch/http/parameters.rb



56
57
58
59
60
61
62
# File 'lib/active_model_serializers/register_jsonapi_renderer.rb', line 56

def self.parser
  lambda do |body|
    data = JSON.parse(body)
    data = { _json: data } unless data.is_a?(Hash)
    data.with_indifferent_access
  end
end