diff --git a/src/cache.js b/src/cache.js index 819304b..953f445 100644 --- a/src/cache.js +++ b/src/cache.js @@ -1,7 +1,7 @@ import DataLoader from 'dataloader' import { getCollection, isModel } from './helpers' - +import { ObjectId } from 'bson' // https://github.com/graphql/dataloader#batch-function const orderDocs = ids => docs => { const idMap = {} @@ -29,14 +29,15 @@ export const createCachingMethods = ({ collection, model, cache }) => { const methods = { findOneById: async (id, { ttl } = {}) => { - const key = cachePrefix + id + const _id = id instanceof ObjectId ? id.toHexString() : id + const key = cachePrefix + _id const cacheDoc = await cache.get(key) if (cacheDoc) { return JSON.parse(cacheDoc) } - const doc = await loader.load(id) + const doc = await loader.load(_id) if (Number.isInteger(ttl)) { // https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-caching#apollo-server-caching cache.set(key, JSON.stringify(doc), { ttl }) @@ -48,8 +49,9 @@ export const createCachingMethods = ({ collection, model, cache }) => { return Promise.all(ids.map(id => methods.findOneById(id, { ttl }))) }, deleteFromCacheById: async id => { - loader.clear(id) - await cache.delete(cachePrefix + id) + const _id = id instanceof ObjectId ? id.toHexString() : id + loader.clear(_id) + await cache.delete(cachePrefix + _id) } }