import DataLoader from "dataloader" ; import { Entity , EntityManager , EntityMetadata } from "../EntityManager" ; import { assertIdsAreTagged , deTagIds } from "../keys" ; import { getOrSet , indexBy } from "../utils" ; export function loadDataLoader < T extends Entity > ( em , meta ) { return getOrSet ( em . loadLoaders , meta . type , ( ) => { return new DataLoader < string , T | undefined > ( async ( _keys ) => { assertIdsAreTagged ( _keys ) ; const keys = deTagIds ( meta , _keys ) ; const rows = await em . driver . load ( em , meta , keys ) ; const entities = rows . map ( ( row ) => em . hydrate ( meta . cstr , row , { overwriteExisting : true } ) ) ; const entitiesById = indexBy ( entities , ( e ) => e . id ! ) ; return _keys . map ( ( k ) => { const entity = entitiesById . get ( k ) ; if ( entity === undefined ) { const existingEntity = em . findExistingInstance < T > ( k ) ; if ( existingEntity ) { existingEntity . __orm . deleted = "deleted" ; } } return entity ; } ) ; } ) ; } ) ; }