import DataLoader from "dataloader" ; import { Entity , EntityManager , getMetadata } from "../EntityManager" ; import { assertIdsAreTagged , deTagIds , getEm , maybeResolveReferenceToId } from "../index" ; import { OneToOneReferenceImpl } from "../relations/OneToOneReference" ; import { getOrSet , groupBy } from "../utils" ; export function oneToOneDataLoader < T extends Entity , U extends Entity > ( em , reference ) { const meta = getMetadata ( reference . entity ) ; const loaderName = `${ meta . tableName }.${ reference . fieldName }` ; return getOrSet ( em . loadLoaders , loaderName , ( ) => { return new DataLoader < string , U | undefined > ( async ( _keys ) => { const { otherMeta , otherFieldName } = reference ; assertIdsAreTagged ( _keys ) ; const keys = deTagIds ( meta , _keys ) ; const em = getEm ( reference . entity ) ; const rows = await em . driver . loadOneToOne ( em , reference , keys ) ; const entities = rows . map ( ( row ) => em . hydrate ( otherMeta . cstr , row , { overwriteExisting : false } ) ) ; const rowsById = groupBy ( entities , ( entity ) => { const ownerId = maybeResolveReferenceToId ( entity . __orm . data [ otherFieldName ] ) ; return ownerId ?? "dummyNoLongerOwned" ; } ) ; return _keys . map ( ( k ) => rowsById . get ( k ) ?. [ 0 ] as U | undefined ) ; } ) ; } ) ; }