Skip to content

Commit d54d7f1

Browse files
committed
rename and slighly refactor primeLoader
1 parent 913e8f3 commit d54d7f1

2 files changed

Lines changed: 16 additions & 9 deletions

File tree

src/cache.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { KeyValueCache } from "apollo-server-caching";
33
import DataLoader from "dataloader";
44
import { EJSON } from "bson";
55
import { CosmosDataSourceOptions } from "./datasource";
6+
import { isArray } from "util";
67

78
// https://github.com/graphql/dataloader#batch-function
89
const 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

5556
export 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
};

src/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
1-
export { CosmosDataSource } from "./datasource";
1+
import { CosmosDataSource } from "./datasource";
2+
import { FindArgs } from "./cache";
3+
4+
export { CosmosDataSource, FindArgs };

0 commit comments

Comments
 (0)