-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcached_resources_processor.rb
39 lines (34 loc) · 1.13 KB
/
cached_resources_processor.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'jsonapi/renderer/resources_processor'
module JSONAPI
class Renderer
# @private
class CachedResourcesProcessor < ResourcesProcessor
class JSONString < String
end
def initialize(cache)
@cache = cache
end
def process_resources
[@primary, @included].each do |resources|
cache_hash = cache_key_map(resources)
processed_resources = @cache.fetch_multi(*cache_hash.keys) do |key|
res, include, fields = cache_hash[key]
res.as_jsonapi(include: include, fields: fields)
end
resources.replace(processed_resources.values)
end
end
def cache_key_map(resources)
resources.each_with_object({}) do |res, h|
ri = [res.jsonapi_type, res.jsonapi_id]
include_rels = @include_rels[ri]
# Sort for cache key consistency
include_dir = include_rels.keys.sort unless include_rels.nil?
fields = @fields[ri.first.to_sym]
h[res.jsonapi_cache_key(include: include_dir, fields: fields)] =
[res, include_dir, fields]
end
end
end
end
end