import DataLoader , { BatchLoadFn } from 'dataloader' ; import { GraphQLResolveInfo } from 'graphql-compose/lib/graphql' ; export function getDataLoader < TContext extends Record < any , any > = any > ( context , info , batchLoadFn ) { if ( ! context . _gqlDataLoaders ) ( context as any ) . _gqlDataLoaders = new WeakMap ( ) ; const { _gqlDataLoaders } = context ; const dlKey = info . fieldNodes ; let dl = _gqlDataLoaders . get ( dlKey ) ; if ( ! dl ) { const dataLoaderOptions = { cacheKeyFn : ( k ) => { if ( k ?. equals ) { return k . toString ( ) ; } return k ; } , } as DataLoader . Options < any , any , any > ; dl = new DataLoader ( async ( ids ) => { const result = await batchLoadFn ( ids ) ; return ids . map ( ( id ) => ( result as any ) . find ( ( doc ) => { if ( doc ?. _id ?. equals ) { return doc . _id . equals ( id ) ; } return doc . _id === id ; } ) ) ; } , dataLoaderOptions ) ; _gqlDataLoaders . set ( dlKey , dl ) ; } return dl ; }