Skip to content

Commit c8b0816

Browse files
committed
Allow resource level links to be defined
Graphiti supports links at a relationship level and at the top-level of the jsonapi document. Relationship level links are mainly to support lazy loading, and top level links are used solely for pagination. This commit adds support for defining links at the resource level. These links could be used to provide the URL to the resource, or alternative representation of the resource, or even actions to perform against the resource. { "data": { "id": 1, "type": "tests", "attributes": {}, "relationships": {}, "links": { "self": "http://test.com/api/v1/tests/1" } } } To define a link on a resource: link :self do |model| "#{self.endpoint[:url]}/#{model.id}" end
1 parent 1cef192 commit c8b0816

File tree

4 files changed

+21
-0
lines changed

4 files changed

+21
-0
lines changed

lib/graphiti/resource.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,5 +148,16 @@ def transaction
148148
end
149149
response
150150
end
151+
152+
def links?
153+
self.class.links.any?
154+
end
155+
156+
def links(model)
157+
self.class.links.inject({}) do |memo, (name, blk)|
158+
memo[name] = instance_exec(model, &blk)
159+
memo
160+
end
161+
end
151162
end
152163
end

lib/graphiti/resource/configuration.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ def config
198198
extra_attributes: {},
199199
sideloads: {},
200200
callbacks: {},
201+
links: {},
201202
}
202203
end
203204

@@ -236,6 +237,10 @@ def pagination
236237
def default_filters
237238
config[:default_filters]
238239
end
240+
241+
def links
242+
config[:links]
243+
end
239244
end
240245

241246
def get_attr!(name, flag, options = {})

lib/graphiti/resource/dsl.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,10 @@ def on_extra_attribute(name, &blk)
146146
end
147147
end
148148

149+
def link(name, &blk)
150+
config[:links][name.to_sym] = blk
151+
end
152+
149153
def all_attributes
150154
attributes.merge(extra_attributes)
151155
end

lib/graphiti/serializer.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def self.inherited(klass)
2525
def as_jsonapi(*)
2626
super.tap do |hash|
2727
strip_relationships!(hash) if strip_relationships?
28+
hash[:links] = @resource.links(@object) if @resource.links?
2829
end
2930
end
3031

0 commit comments

Comments
 (0)