Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/cache.js
Original file line number Diff line number Diff line change
@@ -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 = {}
Expand Down Expand Up @@ -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 })
Expand All @@ -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)
}
}

Expand Down