Skip to content

A platform for community discussion. Free, open, simple.

1.1 KB
Raw Blame
# frozen_string_literal: true

module JsonApiKit
  class Document
    class ResourceObject
      delegate :id, to: :record, private: true
      delegate :glossary, :urls, to: :client, private: true
      delegate :member_type, :member_relationship, :member_attributes, to: :glossary, private: true

      def initialize(record, client:, fieldsets:, meta: {})
        @record = record
        @client = client
        @fieldsets = fieldsets
        @meta = meta
      end

      def to_h = { type:, id:, attributes:, relationships:, links:, meta: }.compact_blank

      private

      attr_reader :record, :client, :fieldsets, :meta

      def type = member_type(record.type)

      def attributes
        fieldsets.keep(type, member_attributes(record.attributes).transform_keys(&:value))
      end

      def relationships
        record.relationships.to_h do |name, linkage|
          [
            member_relationship(declared: name, type: record.type),
            RelationshipObject.new(linkage, client:, owner: record, name:).to_h,
          ]
        end
      end

      def links = { self: urls.for(record).to_s }
    end
  end
end