Class: JSONAPI::ResourceSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi/resource_serializer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(primary_resource_klass, options = {}) ⇒ ResourceSerializer

initialize Options can include include:

Purpose: determines which objects will be side loaded with the source objects in a linked section
Example: ['comments','author','comments.tags','author.posts']

fields:

Purpose: determines which fields are serialized for a resource type. This encompasses both attributes and
         relationship ids in the links section for a resource. Fields are global for a resource type.
Example: { people: [:id, :email, :comments], posts: [:id, :title, :author], comments: [:id, :body, :post]}

key_formatter: KeyFormatter instance to override the default configuration serialization_options: additional options that will be passed to resource meta and links lambdas



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/jsonapi/resource_serializer.rb', line 20

def initialize(primary_resource_klass, options = {})
  @primary_resource_klass = primary_resource_klass
  @primary_class_name     = primary_resource_klass._type
  @fields                 = options.fetch(:fields, {})
  @include                = options.fetch(:include, [])
  @include_directives     = options[:include_directives]
  @include_directives     ||= JSONAPI::IncludeDirectives.new(@primary_resource_klass, @include)
  @key_formatter          = options.fetch(:key_formatter, JSONAPI.configuration.key_formatter)
  @id_formatter           = ValueFormatter.value_formatter_for(:id)
  @link_builder           = generate_link_builder(primary_resource_klass, options)
  @always_include_to_one_linkage_data = options.fetch(:always_include_to_one_linkage_data,
                                                      JSONAPI.configuration.always_include_to_one_linkage_data)
  @always_include_to_many_linkage_data = options.fetch(:always_include_to_many_linkage_data,
                                                       JSONAPI.configuration.always_include_to_many_linkage_data)
  @serialization_options = options.fetch(:serialization_options, {})

  # Warning: This makes ResourceSerializer non-thread-safe. That's not a problem with the
  # request-specific way it's currently used, though.
  @value_formatter_type_cache = NaiveCache.new{|arg| ValueFormatter.value_formatter_for(arg) }

  @_config_keys = {}
  @_supplying_attribute_fields = {}
  @_supplying_relationship_fields = {}
end

Instance Attribute Details

#always_include_to_many_linkage_dataObject (readonly)

Returns the value of attribute always_include_to_many_linkage_data.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def always_include_to_many_linkage_data
  @always_include_to_many_linkage_data
end

#always_include_to_one_linkage_dataObject (readonly)

Returns the value of attribute always_include_to_one_linkage_data.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def always_include_to_one_linkage_data
  @always_include_to_one_linkage_data
end

#fieldsObject (readonly)

Returns the value of attribute fields.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def fields
  @fields
end

#include_directivesObject (readonly)

Returns the value of attribute include_directives.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def include_directives
  @include_directives
end

#key_formatterObject (readonly)

Returns the value of attribute key_formatter.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def key_formatter
  @key_formatter
end

Returns the value of attribute link_builder.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def link_builder
  @link_builder
end

#primary_class_nameObject (readonly)

Returns the value of attribute primary_class_name.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def primary_class_name
  @primary_class_name
end

#serialization_optionsObject (readonly)

Returns the value of attribute serialization_options.



4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def serialization_options
  @serialization_options
end

Instance Method Details

#config_description(resource_klass) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/jsonapi/resource_serializer.rb', line 129

def config_description(resource_klass)
  {
    class_name: self.class.name,
    seriserialization_options: serialization_options.sort.map(&:as_json),
    supplying_attribute_fields: supplying_attribute_fields(resource_klass).sort,
    supplying_relationship_fields: supplying_relationship_fields(resource_klass).sort,
    link_builder_base_url: link_builder.base_url,
    route_formatter_class: link_builder.route_formatter.uncached.class.name,
    key_formatter_class: key_formatter.uncached.class.name,
    always_include_to_one_linkage_data: always_include_to_one_linkage_data,
    always_include_to_many_linkage_data: always_include_to_many_linkage_data
  }
end

#config_key(resource_klass) ⇒ Object



121
122
123
124
125
126
127
# File 'lib/jsonapi/resource_serializer.rb', line 121

def config_key(resource_klass)
  @_config_keys.fetch resource_klass do
    desc = self.config_description(resource_klass).map(&:inspect).join(",")
    key = JSONAPI.configuration.resource_cache_digest_function.call(desc)
    @_config_keys[resource_klass] = "SRLZ-#{key}"
  end
end

#format_key(key) ⇒ Object



113
114
115
# File 'lib/jsonapi/resource_serializer.rb', line 113

def format_key(key)
  @key_formatter.format(key)
end

#format_value(value, format) ⇒ Object



117
118
119
# File 'lib/jsonapi/resource_serializer.rb', line 117

def format_value(value, format)
  @value_formatter_type_cache.get(format).format(value)
end

#object_hash(source, include_directives = {}) ⇒ Object

Returns a serialized hash for the source model



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/jsonapi/resource_serializer.rb', line 144

def object_hash(source, include_directives = {})
  obj_hash = {}

  if source.is_a?(JSONAPI::CachedResourceFragment)
    obj_hash['id'] = source.id
    obj_hash['type'] = source.type

    obj_hash['links'] = source.links_json if source.links_json
    obj_hash['attributes'] = source.attributes_json if source.attributes_json

    relationships = cached_relationships_hash(source, include_directives)
    obj_hash['relationships'] = relationships unless relationships.empty?

    obj_hash['meta'] = source.meta_json if source.meta_json
  else
    fetchable_fields = Set.new(source.fetchable_fields)

    # TODO Should this maybe be using @id_formatter instead, for consistency?
    id_format = source.class._attribute_options(:id)[:format]
    # protect against ids that were declared as an attribute, but did not have a format set.
    id_format = 'id' if id_format == :default
    obj_hash['id'] = format_value(source.id, id_format)

    obj_hash['type'] = format_key(source.class._type.to_s)

    links = links_hash(source)
    obj_hash['links'] = links unless links.empty?

    attributes = attributes_hash(source, fetchable_fields)
    obj_hash['attributes'] = attributes unless attributes.empty?

    relationships = relationships_hash(source, fetchable_fields, include_directives)
    obj_hash['relationships'] = relationships unless relationships.nil? || relationships.empty?

    meta = meta_hash(source)
    obj_hash['meta'] = meta unless meta.empty?
  end

  obj_hash
end


109
110
111
# File 'lib/jsonapi/resource_serializer.rb', line 109

def query_link(query_params)
  link_builder.query_link(query_params)
end

#serialize_to_hash(source) ⇒ Object

Converts a single resource, or an array of resources to a hash, conforming to the JSONAPI structure



46
47
48
49
50
51
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
# File 'lib/jsonapi/resource_serializer.rb', line 46

def serialize_to_hash(source)
  @top_level_sources = Set.new([source].flatten(1).compact.map {|s| top_level_source_key(s) })

  is_resource_collection = source.respond_to?(:to_ary)

  @included_objects = {}

  process_source_objects(source, @include_directives.include_directives)

  primary_objects = []

  # pull the processed objects corresponding to the source objects. Ensures we preserve order.
  if is_resource_collection
    source.each do |primary|
      if primary.id
        case primary
          when CachedResourceFragment then primary_objects.push(@included_objects[primary.type][primary.id][:object_hash])
          when Resource then primary_objects.push(@included_objects[primary.class._type][primary.id][:object_hash])
          else raise "Unknown source type #{primary.inspect}"
        end
      end
    end
  else
    if source.try(:id)
      case source
        when CachedResourceFragment then primary_objects.push(@included_objects[source.type][source.id][:object_hash])
        when Resource then primary_objects.push(@included_objects[source.class._type][source.id][:object_hash])
        else raise "Unknown source type #{source.inspect}"
      end
    end
  end

  included_objects = []
  @included_objects.each_value do |objects|
    objects.each_value do |object|
      unless object[:primary]
        included_objects.push(object[:object_hash])
      end
    end
  end

  primary_hash = { data: is_resource_collection ? primary_objects : primary_objects[0] }

  primary_hash[:included] = included_objects if included_objects.size > 0
  primary_hash
end


93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/jsonapi/resource_serializer.rb', line 93

def serialize_to_links_hash(source, requested_relationship)
  if requested_relationship.is_a?(JSONAPI::Relationship::ToOne)
    data = to_one_linkage(source, requested_relationship)
  else
    data = to_many_linkage(source, requested_relationship)
  end

  {
    links: {
      self: self_link(source, requested_relationship),
      related: related_link(source, requested_relationship)
    },
    data: data
  }
end