UNPKG

2.95 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.QueryCache = exports.DataLoaderCache = exports.DataLoaderExecutor = void 0;
7const dataloader_1 = __importDefault(require("dataloader"));
8const errors_1 = require("./errors");
9const object_hash_1 = __importDefault(require("object-hash"));
10class DataLoaderExecutor {
11 constructor(connection, strategies) {
12 this.connection = connection;
13 this.strategies = strategies;
14 }
15}
16exports.DataLoaderExecutor = DataLoaderExecutor;
17class DataLoaderCache {
18 constructor(read) {
19 this._map = new WeakMap();
20 this._read = read;
21 }
22 get(executor) {
23 let loader = this._map.get(executor);
24 if (loader) {
25 return loader;
26 }
27 const read = this._read;
28 loader = new dataloader_1.default(async function (ids) {
29 var _a;
30 // Get the results from the read in whatever order the database found
31 // most efficient.
32 const results = await read(executor, ids);
33 // Index the results by ID.
34 const resultsById = new Map();
35 for (let i = 0; i < results.length; i++) {
36 const result = results[i];
37 resultsById.set(result.id, result);
38 }
39 // Normalize the order and format to comply with the DataLoader interface.
40 const returnValue = new Array(ids.length);
41 for (let i = 0; i < ids.length; i++) {
42 const id = ids[i];
43 returnValue[i] = (_a = resultsById.get(id)) !== null && _a !== void 0 ? _a : new errors_1.NotFoundError();
44 }
45 return returnValue;
46 });
47 this._map.set(executor, loader);
48 return loader;
49 }
50}
51exports.DataLoaderCache = DataLoaderCache;
52class QueryCache {
53 constructor() {
54 this._map = new WeakMap();
55 }
56 query(tx, query, parameters) {
57 // Queries using a direct connection or connection pool bypass the cache.
58 if (!(tx instanceof DataLoaderExecutor)) {
59 return tx.query(query, parameters);
60 }
61 // Load a cache map keyed by the executor.
62 let cache = this._map.get(tx);
63 if (!cache) {
64 cache = new Map();
65 this._map.set(tx, cache);
66 }
67 // A hash of the entire query and parameters is used as the key.
68 const hash = object_hash_1.default({ query, parameters });
69 // Return cached results or populate the cache with new pending results.
70 let result = cache.get(hash);
71 if (!result) {
72 result = tx.connection.query(query, parameters);
73 cache.set(hash, result);
74 }
75 return result;
76 }
77}
78exports.QueryCache = QueryCache;
79//# sourceMappingURL=loader.js.map
\No newline at end of file