forked from GraphQLGuide/apollo-datasource-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.test.js
304 lines (246 loc) · 8.82 KB
/
cache.test.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import { InMemoryLRUCache } from 'apollo-server-caching'
import wait from 'waait'
import { ObjectId } from 'mongodb'
import { EJSON } from 'bson'
import {
createCachingMethods,
idToString,
isValidObjectIdString
} from '../cache'
const hexId = '5cf82e14a220a607eb64a7d4'
const docs = {
one: {
_id: ObjectId(hexId),
foo: 'bar',
tags: ['foo', 'bar']
},
two: {
_id: ObjectId(),
foo: 'bar'
}
}
const stringDoc = {
_id: 's2QBCnv6fXv5YbjAP',
tags: ['bar', 'baz']
}
const collectionName = 'test'
const cacheKeyById = id => `mongo-${collectionName}-${idToString(id)}`
const cacheKeyByFields = fields => {
const cleanedFields = {}
Object.keys(fields).forEach(key => {
if (typeof key !== 'undefined') {
cleanedFields[key] = Array.isArray(fields[key])
? fields[key]
: [fields[key]]
}
})
return `mongo-${collectionName}-${JSON.stringify(cleanedFields)}`
}
describe('createCachingMethods', () => {
let collection
let api
let cache
beforeEach(() => {
collection = {
collectionName,
find: jest.fn(filter => {
return {
toArray: () =>
new Promise(resolve => {
setTimeout(
() =>
resolve(
[docs.one, docs.two, stringDoc].filter(doc => {
for (const orFilter of filter.$or || [filter]) {
for (const field in orFilter) {
if (field === '_id') {
for (const id of orFilter._id.$in) {
if (id.equals && !id.equals(doc._id)) {
break
} else if (
doc._id.equals &&
!doc._id.equals(id)
) {
break
} else if (
!id.equals &&
!doc._id.equals &&
id !== doc._id
) {
break
}
}
} else if (Array.isArray(doc[field])) {
for (const value of orFilter[field].$in) {
if (!doc[field].includes(value)) {
break
}
}
} else if (
!orFilter[field].$in.includes(doc[field])
) {
break
}
}
return true
}
return false
})
),
0
)
})
}
})
}
cache = new InMemoryLRUCache()
api = createCachingMethods({ collection, cache })
})
it('adds the right methods', () => {
expect(api.findOneById).toBeDefined()
expect(api.findManyByIds).toBeDefined()
expect(api.deleteFromCacheById).toBeDefined()
expect(api.findByFields).toBeDefined()
expect(api.deleteFromCacheByFields).toBeDefined()
})
it('finds one with ObjectId', async () => {
const doc = await api.findOneById(docs.one._id)
expect(doc).toBe(docs.one)
expect(collection.find.mock.calls.length).toBe(1)
})
it('finds one with string id', async () => {
const doc = await api.findOneById(stringDoc._id)
expect(doc).toBe(stringDoc)
expect(collection.find.mock.calls.length).toBe(1)
})
it('finds two with batching', async () => {
const foundDocs = await api.findManyByIds([docs.one._id, docs.two._id])
expect(foundDocs[0]).toBe(docs.one)
expect(foundDocs[1]).toBe(docs.two)
expect(collection.find.mock.calls.length).toBe(1)
})
it(`memoizes with Dataloader`, async () => {
await api.findOneById(docs.one._id)
await api.findOneById(docs.one._id)
expect(collection.find.mock.calls.length).toBe(1)
})
it('finds by field', async () => {
const foundDocs = await api.findByFields({ foo: 'bar' })
expect(foundDocs[0]).toBe(docs.one)
expect(foundDocs[1]).toBe(docs.two)
expect(foundDocs.length).toBe(2)
expect(collection.find.mock.calls.length).toBe(1)
})
it('finds by ObjectID field', async () => {
const foundDocs = await api.findByFields({ _id: ObjectId(hexId) })
expect(foundDocs[0]).toBe(docs.one)
expect(foundDocs.length).toBe(1)
expect(collection.find.mock.calls.length).toBe(1)
})
it('finds by array field', async () => {
const foundDocs = await api.findByFields({ tags: 'bar' })
expect(foundDocs[0]).toBe(docs.one)
expect(foundDocs[1]).toBe(stringDoc)
expect(foundDocs.length).toBe(2)
expect(collection.find.mock.calls.length).toBe(1)
})
it('finds by multiple fields', async () => {
const foundDocs = await api.findByFields({
tags: ['foo', 'bar'],
foo: 'bar'
})
expect(foundDocs[0]).toBe(docs.one)
expect(foundDocs.length).toBe(1)
expect(collection.find.mock.calls.length).toBe(1)
})
it(`doesn't mix filters of pending calls for different fields`, async () => {
const pendingDocs1 = api.findByFields({ foo: 'bar' })
const pendingDocs2 = api.findByFields({ tags: 'baz' })
const [foundDocs1, foundDocs2] = await Promise.all([
pendingDocs1,
pendingDocs2
])
expect(foundDocs1[0]).toBe(docs.one)
expect(foundDocs1[1]).toBe(docs.two)
expect(foundDocs1.length).toBe(2)
expect(foundDocs2[0]).toBe(stringDoc)
expect(foundDocs2.length).toBe(1)
expect(collection.find.mock.calls.length).toBe(1)
})
it(`dataloader caches each value individually when finding by a single field`, async () => {
await api.findByFields({ tags: ['foo', 'baz'] }, { ttl: 1 })
const fooBazCacheValue = await cache.get(
cacheKeyByFields({ tags: ['foo', 'baz'] })
)
const fooCacheValue = await cache.get(cacheKeyByFields({ tags: 'foo' }))
expect(fooBazCacheValue).toBeDefined()
expect(fooCacheValue).toBeUndefined()
await api.findByFields({ tags: 'foo' })
expect(collection.find.mock.calls.length).toBe(1)
})
it(`doesn't cache without ttl`, async () => {
await api.findOneById(docs.one._id)
const value = await cache.get(cacheKeyById(docs.one._id))
expect(value).toBeUndefined()
})
it(`caches by ID`, async () => {
await api.findOneById(docs.one._id, { ttl: 1 })
const value = await cache.get(cacheKeyById(docs.one._id))
expect(value).toEqual(EJSON.stringify(docs.one))
await api.findOneById(docs.one._id)
expect(collection.find.mock.calls.length).toBe(1)
})
it(`caches non-array field values as arrays`, async () => {
const fields = { tags: 'foo' }
await api.findByFields(fields, { ttl: 1 })
const value = await cache.get(cacheKeyByFields(fields))
expect(value).toEqual(EJSON.stringify([docs.one]))
await api.findByFields({ tags: ['foo'] })
expect(collection.find.mock.calls.length).toBe(1)
})
it(`caches ID with ttl`, async () => {
await api.findOneById(docs.one._id, { ttl: 1 })
await wait(1001)
const value = await cache.get(cacheKeyById(docs.one._id))
expect(value).toBeUndefined()
})
it(`deletes from cache by ID`, async () => {
for (const doc of [docs.one, docs.two, stringDoc]) {
await api.findOneById(doc._id, { ttl: 1 })
const valueBefore = await cache.get(cacheKeyById(doc._id))
expect(valueBefore).toEqual(EJSON.stringify(doc))
await api.deleteFromCacheById(doc._id)
const valueAfter = await cache.get(cacheKeyById(doc._id))
expect(valueAfter).toBeUndefined()
}
})
it('deletes from DataLoader cache by ID', async () => {
for (const id of [docs.one._id, docs.two._id, stringDoc._id]) {
await api.findOneById(id)
expect(collection.find).toHaveBeenCalled()
collection.find.mockClear()
await api.findOneById(id)
expect(collection.find).not.toHaveBeenCalled()
await api.deleteFromCacheById(id)
await api.findOneById(id)
expect(collection.find).toHaveBeenCalled()
}
})
it(`deletes from cache by fields`, async () => {
const fields = { foo: 'bar' }
await api.findByFields(fields, { ttl: 1 })
const valueBefore = await cache.get(cacheKeyByFields(fields))
expect(valueBefore).toEqual(EJSON.stringify([docs.one, docs.two]))
await api.deleteFromCacheByFields(fields)
const valueAfter = await cache.get(cacheKeyByFields(fields))
expect(valueAfter).toBeUndefined()
})
})
describe('isValidObjectIdString', () => {
it('works', () => {
const trickyId = 'toptoptoptop'
expect(ObjectId.isValid(trickyId)).toBe(true)
expect(isValidObjectIdString(trickyId)).toBe(false)
expect(isValidObjectIdString(hexId)).toBe(true)
})
})