1
1
import DataLoader from 'dataloader'
2
2
3
3
import { getCollection , isModel } from './helpers'
4
-
4
+ import { ObjectId } from 'bson'
5
5
// https://github.com/graphql/dataloader#batch-function
6
6
const orderDocs = ids => docs => {
7
7
const idMap = { }
@@ -29,14 +29,15 @@ export const createCachingMethods = ({ collection, model, cache }) => {
29
29
30
30
const methods = {
31
31
findOneById : async ( id , { ttl } = { } ) => {
32
- const key = cachePrefix + id
32
+ const _id = id instanceof ObjectId ? id . toHexString ( ) : id
33
+ const key = cachePrefix + _id
33
34
34
35
const cacheDoc = await cache . get ( key )
35
36
if ( cacheDoc ) {
36
37
return JSON . parse ( cacheDoc )
37
38
}
38
39
39
- const doc = await loader . load ( id )
40
+ const doc = await loader . load ( _id )
40
41
if ( Number . isInteger ( ttl ) ) {
41
42
// https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-caching#apollo-server-caching
42
43
cache . set ( key , JSON . stringify ( doc ) , { ttl } )
@@ -48,8 +49,9 @@ export const createCachingMethods = ({ collection, model, cache }) => {
48
49
return Promise . all ( ids . map ( id => methods . findOneById ( id , { ttl } ) ) )
49
50
} ,
50
51
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 )
53
55
}
54
56
}
55
57
0 commit comments