From f07b9558a6ac4d86dd671127d6a2d62b19dd4f9a Mon Sep 17 00:00:00 2001 From: Alessandro Magionami Date: Mon, 10 Jul 2023 18:12:44 +0200 Subject: [PATCH] feat(main-loader): optimize memory usage for createQueriesMap in class --- packages/main-loader/lib/main-loader.ts | 51 +++++++++++++++++-------- 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/packages/main-loader/lib/main-loader.ts b/packages/main-loader/lib/main-loader.ts index ef36166..de09b94 100644 --- a/packages/main-loader/lib/main-loader.ts +++ b/packages/main-loader/lib/main-loader.ts @@ -1,32 +1,44 @@ -import DataLoader, { BatchLoadFn } from 'dataloader'; +import DataLoader, { BatchLoadFn } from "dataloader"; -import { hash } from './hash'; -import type { Key } from './key'; -import { createQueriesMapFactory } from './create-queries-map-factory'; +import { hash } from "./hash"; +import type { Key } from "./key"; +import { createQueriesMapFactory } from "./create-queries-map-factory"; -export abstract class MainLoader, 'query' | 'skip' | 'limit'> = Key> { +const createQueriesMap = createQueriesMapFactory(); + +export abstract class MainLoader< + TReturn, + TQuery extends object, + TLoadKey extends Pick, "query" | "skip" | "limit"> = Key +> { protected loader: DataLoader, TReturn>; - protected createQueriesMap; constructor() { this.loader = new DataLoader, TReturn, string>( this.batchLoadFn.bind(this) as BatchLoadFn, TReturn>, { cacheKeyFn: this.cacheKeyFn, - }, + } ); - this.createQueriesMap = createQueriesMapFactory() } - public async load(key: TLoadKey): Promise { + public async load( + key: TLoadKey + ): Promise { const internalKey = this.preLoad(key); return this.loader.load(internalKey) as Promise; } - public async loadMany(key: TLoadKey): Promise { + public async loadMany( + key: TLoadKey + ): Promise { const internalKey = this.preLoad(key); - const { skip, limit } = key - return this.loader.load({ skip: skip ?? 0, limit: limit ?? 0, ...internalKey }) as Promise; + const { skip, limit } = key; + return this.loader.load({ + skip: skip ?? 0, + limit: limit ?? 0, + ...internalKey, + }) as Promise; } protected async batchLoadFn(keys: readonly Key[]) { @@ -48,9 +60,18 @@ export abstract class MainLoader { return key as unknown as Key } + private createQueriesMap(keys: readonly Key[]) { + return createQueriesMap(keys); + } + + protected preLoad(key: TLoadKey): Key { + return key as unknown as Key; + } - protected onError(error: Error, key: Key) {} + protected onError(error: Error, key: Key) { } - protected abstract execute(key: Key, options?: unknown): Promise; + protected abstract execute( + key: Key, + options?: unknown + ): Promise; }