Skip to content

Commit d0bcb4f

Browse files
authored
Fix duplicate ObjectId keys (#37)
* Fix duplicate ObjectId keys * Fix can't delete ObjectId lead to memory leak
1 parent 553cfd3 commit d0bcb4f

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/cache.js

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import DataLoader from 'dataloader'
22

33
import { getCollection, isModel } from './helpers'
4-
4+
import { ObjectId } from 'bson'
55
// https://github.com/graphql/dataloader#batch-function
66
const orderDocs = ids => docs => {
77
const idMap = {}
@@ -29,14 +29,15 @@ export const createCachingMethods = ({ collection, model, cache }) => {
2929

3030
const methods = {
3131
findOneById: async (id, { ttl } = {}) => {
32-
const key = cachePrefix + id
32+
const _id = id instanceof ObjectId ? id.toHexString() : id
33+
const key = cachePrefix + _id
3334

3435
const cacheDoc = await cache.get(key)
3536
if (cacheDoc) {
3637
return JSON.parse(cacheDoc)
3738
}
3839

39-
const doc = await loader.load(id)
40+
const doc = await loader.load(_id)
4041
if (Number.isInteger(ttl)) {
4142
// https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-caching#apollo-server-caching
4243
cache.set(key, JSON.stringify(doc), { ttl })
@@ -48,8 +49,9 @@ export const createCachingMethods = ({ collection, model, cache }) => {
4849
return Promise.all(ids.map(id => methods.findOneById(id, { ttl })))
4950
},
5051
deleteFromCacheById: async id => {
51-
loader.clear(id)
52-
await cache.delete(cachePrefix + id)
52+
const _id = id instanceof ObjectId ? id.toHexString() : id
53+
loader.clear(_id)
54+
await cache.delete(cachePrefix + _id)
5355
}
5456
}
5557

0 commit comments

Comments
 (0)