1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | Object.defineProperty(exports, "__esModule", { value: true });
|
6 | exports.QueryCache = exports.DataLoaderCache = exports.DataLoaderExecutor = void 0;
|
7 | const dataloader_1 = __importDefault(require("dataloader"));
|
8 | const errors_1 = require("./errors");
|
9 | const object_hash_1 = __importDefault(require("object-hash"));
|
10 | class DataLoaderExecutor {
|
11 | constructor(connection, strategies) {
|
12 | this.connection = connection;
|
13 | this.strategies = strategies;
|
14 | }
|
15 | }
|
16 | exports.DataLoaderExecutor = DataLoaderExecutor;
|
17 | class 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 |
|
31 |
|
32 | const results = await read(executor, ids);
|
33 |
|
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 |
|
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 | }
|
51 | exports.DataLoaderCache = DataLoaderCache;
|
52 | class QueryCache {
|
53 | constructor() {
|
54 | this._map = new WeakMap();
|
55 | }
|
56 | query(tx, query, parameters) {
|
57 |
|
58 | if (!(tx instanceof DataLoaderExecutor)) {
|
59 | return tx.query(query, parameters);
|
60 | }
|
61 |
|
62 | let cache = this._map.get(tx);
|
63 | if (!cache) {
|
64 | cache = new Map();
|
65 | this._map.set(tx, cache);
|
66 | }
|
67 |
|
68 | const hash = object_hash_1.default({ query, parameters });
|
69 |
|
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 | }
|
78 | exports.QueryCache = QueryCache;
|
79 |
|
\ | No newline at end of file |