import { Entity , EntityConstructor , getMetadata } from "./EntityManager" ; import { LoadHint } from "./loaded" ; import { fail } from "./utils" ; /**
 * Given a load hint of "given an entity, load these N things", return an array
 * of what those N things are, and reversed load hints to "come back" to the
 * original entity.
 */ export function reverseHint < T extends Entity > ( entityType , hint ) { if ( typeof hint === "string" ) { const meta = getMetadata ( entityType ) ; const field = meta . fields [ hint ] || fail ( `Invalid hint ${ entityType . name } ${ JSON . stringify ( hint ) }` ) ; if ( field . kind !== "m2m" && field . kind !== "m2o" && field . kind !== "o2m" && field . kind !== "o2o" ) { throw new Error ( "Invalid hint" ) ; } const otherMeta = field . otherMetadata ( ) ; return [ [ otherMeta . cstr , [ field . otherFieldName ] ] ] ; } else if ( Array . isArray ( hint ) ) { return ( hint as string [ ] ) . map ( ( hint ) => reverseHint ( entityType , hint as any ) ) . flat ( ) ; } else { return Object . entries ( hint ) . flatMap ( ( [ key , hint ] ) => { const meta = getMetadata ( entityType ) ; const field = meta . fields [ key ] || fail ( `Invalid hint ${ entityType . name } ${ JSON . stringify ( hint ) }` ) ; if ( field . kind !== "m2m" && field . kind !== "m2o" && field . kind !== "o2m" && field . kind !== "o2o" ) { throw new Error ( "Invalid hint" ) ; } const otherMeta = field . otherMetadata ( ) ; const me = [ otherMeta . cstr , [ field . otherFieldName ] ] as [ EntityConstructor < any > , string [ ] ] ; return [ me , ... reverseHint ( otherMeta . cstr , hint ) . map ( ( [ e , hint ] ) => { return [ e , [ ... hint , field . otherFieldName ] ] as [ EntityConstructor < any > , string [ ] ] ; } ) , ] ; } ) ; } }