@@ -3,6 +3,7 @@ import { KeyValueCache } from "apollo-server-caching";
33import DataLoader from "dataloader" ;
44import { EJSON } from "bson" ;
55import { CosmosDataSourceOptions } from "./datasource" ;
6+ import { isArray } from "util" ;
67
78// https://github.com/graphql/dataloader#batch-function
89const orderDocs = < V > ( ids : readonly string [ ] ) => (
@@ -49,7 +50,7 @@ export interface CachedMethods<DType> {
4950 ) => Promise < ( DType | undefined ) [ ] > ;
5051 deleteFromCacheById : ( id : string ) => Promise < void > ;
5152 dataLoader ?: DataLoader < string , DType , string > ;
52- primeCache : ( item : DType , ttl ?: number ) => void ;
53+ primeCache : ( item : DType | DType [ ] , ttl ?: number ) => void ;
5354}
5455
5556export const createCachingMethods = < DType extends { id : string } > ( {
@@ -117,16 +118,19 @@ export const createCachingMethods = <DType extends { id: string }>({
117118 await cache . delete ( cachePrefix + id ) ;
118119 } ,
119120 /**
120- * Loads an item into DataLoader and optionally the cache (if TTL is specified)
121+ * Loads an item or items into DataLoader and optionally the cache (if TTL is specified)
121122 * Use this when running a query outside of the findOneById/findManyByIds methos
122123 * that automatically and transparently do this
123124 */
124- primeCache : ( doc : DType , ttl ?: number ) => {
125- const key = doc . id ;
126- loader . prime ( key , doc ) ;
127- if ( ttl ) {
128- cache . set ( key , EJSON . stringify ( doc ) , { ttl } ) ;
129- }
125+ primeCache : ( docs , ttl ?: number ) => {
126+ docs = isArray ( docs ) ? docs : [ docs ] ;
127+ docs . forEach ( ( doc ) => {
128+ const key = doc . id ;
129+ loader . prime ( key , doc ) ;
130+ if ( ttl ) {
131+ cache . set ( key , EJSON . stringify ( doc ) , { ttl } ) ;
132+ }
133+ } ) ;
130134 } ,
131135 dataLoader : loader ,
132136 } ;
0 commit comments