Links on a relationship can take a callable

This commit is contained in:
Johannes Vetter 2021-01-16 11:45:37 -08:00
parent c3376037e7
commit d7f6963afc
4 changed files with 38 additions and 0 deletions

View File

@ -305,6 +305,17 @@ This will create a `self` reference for the relationship, and a `related` link f
}
```
Relationship links can also be configured to be defined as a callable.
```ruby
has_many :actors, links: -> (object, params) {
{
self: "https://movies.com/#{object.id}/relationships/actors",
next: "https://movies.com/#{object.id}/relationships/actors?page%5Bnumber%5D=2&page%5Bsize%5D=10"
}
}
```
### Meta Per Resource
For every resource in the collection, you can include a meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.

View File

@ -148,6 +148,8 @@ module FastJsonapi
def add_links_hash(record, params, output_hash)
output_hash[key][:links] = if links.is_a?(Symbol)
record.public_send(links)
elsif links.respond_to?(:call)
FastJsonapi.call_proc(links, record, params)
else
links.each_with_object({}) do |(key, method), hash|
Link.new(key: key, method: method).serialize(record, params, hash)

View File

@ -124,3 +124,15 @@ module Cached
end
end
end
class CallableLinksMovieSerializer < ::MovieSerializer
has_many(
:first_two_actors,
id_method_name: :uid,
links: lambda do |record, params|
{ some: record.id, fancy: 'here' }
end
) do |record, params|
record.actors.take(2)
end
end

View File

@ -142,5 +142,18 @@ RSpec.describe JSONAPI::Serializer do
end
end
end
context 'with a callable as relationship links' do
let(:serialized) do
CallableLinksMovieSerializer.new(movie, params).serializable_hash.as_json
end
it do
expect(serialized['data']['relationships']['first_two_actors'])
.to have_link('some').with_value(movie.id)
expect(serialized['data']['relationships']['first_two_actors'])
.to have_link('fancy').with_value('here')
end
end
end
end