Skip to content

Ability to add custom transformation/unpacking of embedded data #153

@thedarkside

Description

@thedarkside

Spyke expects data in the form of

{ 
  data: {
    id: 1,
    attributes: { 
      name: "xy",
      hero: { #<-- embedded resource
        id: 8,
        attributes: {}
      }
    }
  }
}

But apis must not stick to this schema. For example strapi is encapsulating nested objects in a subsequent "data" object like this:

{ 
  data: {
    id: 1,
    attributes: { 
      name: "xy",
      hero: {
        data: { #<-- That one
          id: 8,
          attributes: {}
        }
      }
    }
  }
}

Currently the only way of making that Spyke-compatible is to hook into Faraday and transform the payload before it gets processed by Spyke.

But at this stage we have to iterate over the whole payload and guess. We can't easily rely on the associations configuration in our Spyke models.

A better approach would be to provide a way to change the processing of nested objects if necessary.

Ive created a patch as a poc:

  class Spyke::Base
    # Allows customization via overriding. Per default returns embedded payload untouched.
    def self.unpack_embedded(payload) = payload
  end
  
  class Spyke::Associations::Association
    private
    def embedded_data
      parent.class.unpack_embedded parent.attributes[name]
    end
  end

With this in place i'am now able to override my StrapiBaseRecord to hook into the embedded processing and transform the payload to make it Spyke-compatible.

class StrapiBaseRecord < Spyke::Base
  def self.unpack_embedded(payload)
    # Strapi encodes embedded data nested in a "data" object we need to unpack first.
    payload&.dig(:data)
  end
end

What do you think?
Currently i am using Spyke just to consume payload. No writing involved at all. Therefor i'am not sure this approach is safe for all operations.
For my usecase it's working great!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions