UNPKG

2.32 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(keys => {
23 return Promise.all(keys.map(key => {
24 const [ entityType, id, params = {} ] = key
25 return client.lookup(entityType, id, params).then(entity => {
26 if (entity) {
27 // Store the entity type so we can determine what type of object this
28 // is elsewhere in the code.
29 entity._type = entityType
30 }
31 return entity
32 })
33 }))
34 }, {
35 cacheKeyFn: (key) => client.getLookupURL(...key),
36 cacheMap: cache
37 })
38
39 const browse = new DataLoader(keys => {
40 return Promise.all(keys.map(key => {
41 const [ entityType, params = {} ] = key
42 return client.browse(entityType, params).then(list => {
43 list[toPlural(entityType)].forEach(entity => {
44 // Store the entity type so we can determine what type of object this
45 // is elsewhere in the code.
46 entity._type = entityType
47 })
48 return list
49 })
50 }))
51 }, {
52 cacheKeyFn: (key) => client.getBrowseURL(...key),
53 cacheMap: cache
54 })
55
56 const search = new DataLoader(keys => {
57 return Promise.all(keys.map(key => {
58 const [ entityType, query, params = {} ] = key
59 return client.search(entityType, query, params).then(list => {
60 list[toPlural(entityType)].forEach(entity => {
61 // Store the entity type so we can determine what type of object this
62 // is elsewhere in the code.
63 entity._type = entityType
64 })
65 return list
66 })
67 }))
68 }, {
69 cacheKeyFn: key => client.getSearchURL(...key),
70 cacheMap: cache
71 })
72
73 return { lookup, browse, search }
74}