Sha256: 61402122a2921e8505cfee708e470dc3c431741196b5c92a0402faf7e76ffb1e

Contents?: true

Size: 1.52 KB

Versions: 10

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true
require 'dato/json_schema_relationships'

module Dato
  class JsonApiDeserializer
    attr_reader :link

    def initialize(link)
      @link = link
    end

    def deserialize(data)
      return nil unless data

      data = data[:data]

      if data.is_a? Array
        data.map { |resource| deserialize_resource(resource) }
      else
        deserialize_resource(data)
      end
    end

    def deserialize_resource(data)
      result = { id: data[:id] }

      result[:meta] = data[:meta] if data[:meta]
      result.merge!(data[:attributes]) if data[:attributes]

      if data[:relationships]
        relationships.each do |relationship, meta|
          if data[:relationships][relationship]
            rel_data = data[:relationships][relationship][:data]

            result[relationship] = if meta[:types].length > 1
                                     rel_data
                                   else
                                     if !rel_data
                                       nil
                                     elsif meta[:collection]
                                       rel_data.map { |ref| ref[:id] }
                                     else
                                       rel_data[:id]
                                     end
                                   end
          end
        end
      end

      result.with_indifferent_access
    end

    def relationships
      @relationships ||= JsonSchemaRelationships.new(link.target_schema).relationships
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
dato-0.7.5 lib/dato/json_api_deserializer.rb
dato-0.7.4 lib/dato/json_api_deserializer.rb
dato-0.7.3 lib/dato/json_api_deserializer.rb
dato-0.7.2 lib/dato/json_api_deserializer.rb
dato-0.7.1 lib/dato/json_api_deserializer.rb
dato-0.7.0 lib/dato/json_api_deserializer.rb
dato-0.6.18 lib/dato/json_api_deserializer.rb
dato-0.6.17 lib/dato/json_api_deserializer.rb
dato-0.6.16 lib/dato/json_api_deserializer.rb
dato-0.6.15 lib/dato/json_api_deserializer.rb