Skip to content

Commit fa18645

Browse files
9at8lorensr
andauthored
Clear data loader cache correctly (#46)
* Clear data loader cache correctly, fixes #44 * Add to DataLoader test Co-authored-by: Loren 🤓 <[email protected]>
1 parent 6ce707e commit fa18645

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

src/__tests__/cache.test.js

+25-3
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ import { createCachingMethods, idToString } from '../cache'
77

88
const docs = {
99
id1: {
10-
_id: 'id1'
11-
// _id: ObjectId()
10+
_id: 'aaaa0000bbbb0000cccc0000'
1211
},
1312
id2: {
1413
_id: ObjectId()
@@ -32,7 +31,15 @@ describe('createCachingMethods', () => {
3231
setTimeout(
3332
() =>
3433
resolve(
35-
ids.map(id => (id === docs.id1._id ? docs.id1 : docs.id2))
34+
ids.map(id => {
35+
if (id.equals(new ObjectId(docs.id1._id))) {
36+
return docs.id1
37+
}
38+
39+
if (id.equals(docs.id2._id)) {
40+
return docs.id2
41+
}
42+
})
3643
),
3744
0
3845
)
@@ -111,4 +118,19 @@ describe('createCachingMethods', () => {
111118
expect(valueAfter).toBeUndefined()
112119
}
113120
})
121+
122+
it('deletes from DataLoader cache', async () => {
123+
for (const id of [docs.id1._id, docs.id2._id]) {
124+
await api.findOneById(id)
125+
expect(collection.find).toHaveBeenCalled()
126+
collection.find.mockClear()
127+
128+
await api.findOneById(id)
129+
expect(collection.find).not.toHaveBeenCalled()
130+
131+
await api.deleteFromCacheById(id)
132+
await api.findOneById(id)
133+
expect(collection.find).toHaveBeenCalled()
134+
}
135+
})
114136
})

src/cache.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { EJSON } from 'bson'
55
import { getCollection } from './helpers'
66

77
export const idToString = id => (id instanceof ObjectId ? id.toHexString() : id)
8+
const stringToId = str => str instanceof ObjectId ? str : new ObjectId(str)
89

910
// https://github.com/graphql/dataloader#batch-function
1011
const orderDocs = ids => docs => {
@@ -19,7 +20,7 @@ export const createCachingMethods = ({ collection, model, cache }) => {
1920
const loader = new DataLoader(ids => {
2021
const filter = {
2122
_id: {
22-
$in: ids
23+
$in: ids.map(stringToId)
2324
}
2425
}
2526
const promise = model
@@ -40,7 +41,7 @@ export const createCachingMethods = ({ collection, model, cache }) => {
4041
return EJSON.parse(cacheDoc)
4142
}
4243

43-
const doc = await loader.load(id)
44+
const doc = await loader.load(idToString(id))
4445
if (Number.isInteger(ttl)) {
4546
// https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-caching#apollo-server-caching
4647
cache.set(key, EJSON.stringify(doc), { ttl })

0 commit comments

Comments
 (0)