/* eslint-disable @typescript-eslint/explicit-function-return-type */ import _ from 'lodash'; import DL from 'dataloader'; import { EngineModel } from '@seed/engine/EngineModel'; export class DataLoader extends DL { async loadMany(keys: ArrayLike): Promise> { const nkeys = _.without(keys, undefined, null) as any; const res = await super.loadMany(nkeys); return _.without(res, undefined, null) as any; } } /* V1 - Graph Model */ export const batchFunction = async (model: T, _ids: any, field: string) => { const results = await (await (model as any).db()).find({ [`${field}`]: { $in: _ids } }).toArray(); return _ids.map((_id) => results.find((result) => result[field] === _id)); }; export const batchOneToManyFunction = async (model: T, _ids: any, field: string) => { const results = await (await (model as any).db()).find({ [`${field}`]: { $in: _ids } }).toArray(); return _ids.map((_id) => _.filter(results, { [`${field}`]: _id })); }; export const batchOneToManyFilterFunction = async (model: T, _ids: any, field: string, filter: any) => { const results = await (await (model as any).db()).find({ [`${field}`]: { $in: _ids }, ...filter }).toArray(); return _ids.map((_id) => _.filter(results, { [`${field}`]: _id })); }; export const buildLoader = (model: T, field = '_id') => { return new DataLoader((keys) => { return batchFunction(model, keys, field); }); }; export const buildOneToManyLoader = (model: T, field = '_id') => { return new DataLoader>((keys) => { return batchOneToManyFunction(model, keys, field); }); }; export const buildOneToManyFilterLoader = (model: T, field = '_id', filter: any) => { return new DataLoader>((keys) => { return batchOneToManyFilterFunction(model, keys, field, filter); }); }; /* V2 - Engine Model */ export const batchEngineFunction = async >(model: T, _ids: any, field: string) => { const results = await model.getAll({ query: { [`${field}`]: { $in: _ids } } }); return _ids.map((_id) => results.find((result) => result[field] === _id)); }; export const buildEngineLoader = , V = T>(model: T, field = '_id') => { return new DataLoader((keys) => { return batchEngineFunction(model, keys, field); }); };