1 | import DataLoader from 'dataloader'
|
2 | import LRUCache from 'lru-cache'
|
3 | import { toPlural } from './types/helpers'
|
4 | import { ONE_DAY } from './util'
|
5 |
|
6 | const debug = require('debug')('graphbrainz:loaders')
|
7 |
|
8 | export default function createLoaders (client) {
|
9 |
|
10 |
|
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 |
|
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 |
|
28 |
|
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 |
|
45 |
|
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 |
|
62 |
|
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 | }
|