Module: TypedParams::Formatters::JSONAPI

Defined in:
lib/typed_params/formatters/jsonapi.rb

Overview

The JSONAPI formatter transforms a JSONAPI document into Rails’ standard params format that can be passed to a model.

For example, given the following params:

{
  data: {
    type: 'users',
    id: '1',
    attributes: { email: '[email protected]' },
    relationships: {
      friends: {
        data: [{ type: 'users', id: '2' }]
      }
    }
  }
}

The final params would become:

{
  id: '1',
  email: '[email protected]',
  friend_ids: ['2']
}

Class Method Summary collapse

Class Method Details

.call(params) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/typed_params/formatters/jsonapi.rb', line 35

def self.call(params)
  case params
  in data: Array => data
    format_array_data(data)
  in data: Hash => data
    format_hash_data(data)
  else
    params
  end
end

.format_array_data(data) ⇒ Object



48
49
50
# File 'lib/typed_params/formatters/jsonapi.rb', line 48

def self.format_array_data(data)
  data.map { format_hash_data(_1) }
end

.format_hash_data(data) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/typed_params/formatters/jsonapi.rb', line 52

def self.format_hash_data(data)
  rels  = data[:relationships]
  attrs = data[:attributes]
  res   = data.except(
    :attributes,
    :links,
    :meta,
    :relationships,
    :type,
  )

  # Move attributes over to top-level params
  attrs&.each do |key, attr|
    res[key] = attr
  end

  # Move relationships over. This will use x_id and x_ids when the
  # relationship data only contains :type and :id, otherwise it
  # will use the x_attributes key.
  rels&.each do |key, rel|
    case rel
    # FIXME(ezekg) We need https://bugs.ruby-lang.org/issues/18961 to
    #              clean this up (i.e. remove the if guard).
    in data: [{ type:, id:, **nil }, *] => linkage if linkage.all? { _1 in type:, id:, **nil }
      res[:"#{key.to_s.singularize}_ids"] = linkage.map { _1[:id] }
    in data: []
      res[:"#{key.to_s.singularize}_ids"] = []
    # FIXME(ezekg) Not sure how to make this cleaner, but this handles polymorphic relationships.
    in data: { type:, id:, **nil } if key.to_s.underscore.classify != type.underscore.classify
      res[:"#{key}_type"], res[:"#{key}_id"] = type.underscore.classify, id
    in data: { type:, id:, **nil }
      res[:"#{key}_id"] = id
    in data: nil
      res[:"#{key}_id"] = nil
    else
      # NOTE(ezekg) Embedded relationships are non-standard as per the
      #             JSONAPI spec, but I don't really care. :)
      res[:"#{key}_attributes"] = call(rel)
    end
  end

  res
end