UNPKG

2.6 kBJavaScriptView Raw
1import DataLoader from 'dataloader'
2import LRUCache from 'lru-cache'
3import { toPlural } from './types/helpers'
4import { ONE_DAY } from './util'
5
6const debug = require('debug')('graphbrainz:loaders')
7
8export default function createLoaders(client) {
9 // All loaders share a single LRU cache that will remember 8192 responses,
10 // each cached for 1 day.
11 const cache = LRUCache({
12 max: parseInt(process.env.GRAPHBRAINZ_CACHE_SIZE || 8192, 10),
13 maxAge: parseInt(process.env.GRAPHBRAINZ_CACHE_TTL || ONE_DAY, 10),
14 dispose(key) {
15 debug(`Removed from cache. key=${key}`)
16 }
17 })
18 // Make the cache Map-like.
19 cache.delete = cache.del
20 cache.clear = cache.reset
21
22 const lookup = new DataLoader(
23 keys => {
24 return Promise.all(
25 keys.map(key => {
26 const [entityType, id, params = {}] = key
27 return client.lookup(entityType, id, params).then(entity => {
28 if (entity) {
29 // Store the entity type so we can determine what type of object this
30 // is elsewhere in the code.
31 entity._type = entityType
32 }
33 return entity
34 })
35 })
36 )
37 },
38 {
39 batch: false,
40 cacheKeyFn: key => client.getLookupURL(...key),
41 cacheMap: cache
42 }
43 )
44
45 const browse = new DataLoader(
46 keys => {
47 return Promise.all(
48 keys.map(key => {
49 const [entityType, params = {}] = key
50 return client.browse(entityType, params).then(list => {
51 list[toPlural(entityType)].forEach(entity => {
52 // Store the entity type so we can determine what type of object this
53 // is elsewhere in the code.
54 entity._type = entityType
55 })
56 return list
57 })
58 })
59 )
60 },
61 {
62 batch: false,
63 cacheKeyFn: key => client.getBrowseURL(...key),
64 cacheMap: cache
65 }
66 )
67
68 const search = new DataLoader(
69 keys => {
70 return Promise.all(
71 keys.map(key => {
72 const [entityType, query, params = {}] = key
73 return client.search(entityType, query, params).then(list => {
74 list[toPlural(entityType)].forEach(entity => {
75 // Store the entity type so we can determine what type of object this
76 // is elsewhere in the code.
77 entity._type = entityType
78 })
79 return list
80 })
81 })
82 )
83 },
84 {
85 batch: false,
86 cacheKeyFn: key => client.getSearchURL(...key),
87 cacheMap: cache
88 }
89 )
90
91 return { lookup, browse, search }
92}