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(
|
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 |
|
30 |
|
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 |
|
53 |
|
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 |
|
76 |
|
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 | }
|