import { BaseEntity } from "../BaseEntity" ; import { decoratorMeta } from "../decoratorMeta" ; import { TsDatastoreOrmError } from "../errors/TsDatastoreOrmError" ; import { IEntityMetaOptions } from "../types" ; export function Entity ( options = { } ) { return ( target ) => { let subClassTarget = Object . getPrototypeOf ( target ) ; while ( true ) { if ( ! ( subClassTarget instanceof Function ) ) { break ; } if ( subClassTarget !== BaseEntity ) { if ( decoratorMeta . hasEntityFieldMetaList ( subClassTarget ) ) { const subClassEntityFieldMeta = decoratorMeta . getEntityFieldMetaList ( subClassTarget ) ; for ( const [ fieldName , entityFieldMetaOptions ] of subClassEntityFieldMeta . entries ( ) ) { if ( ! decoratorMeta . hasEntityFieldMeta ( target , fieldName ) ) { decoratorMeta . addEntityFieldMeta ( target , fieldName , entityFieldMetaOptions ) ; } } } decoratorMeta . mergeHooks ( target , subClassTarget ) ; } subClassTarget = Object . getPrototypeOf ( subClassTarget ) ; } if ( ! decoratorMeta . hasEntityFieldMetaList ( target ) ) { throw new TsDatastoreOrmError ( `(${ ( target as any ) . name }) Entity must define an _id field with property decorator @Field().` ) ; } const entityFieldMeta = decoratorMeta . getEntityFieldMetaList ( target ) ; const fieldNames = Array . from ( entityFieldMeta . keys ( ) ) ; if ( ! fieldNames . includes ( "_id" ) ) { throw new TsDatastoreOrmError ( `(${ ( target as any ) . name }) Entity must define an _id field with property decorator @Field().` ) ; } const excludeFromIndexes = [ ] ; for ( const [ fieldName , entityFieldMetaOptions ] of entityFieldMeta . entries ( ) ) { if ( ! entityFieldMetaOptions . index ) { if ( fieldName !== "_id" ) { excludeFromIndexes . push ( fieldName ) ; } } else if ( entityFieldMetaOptions . excludeFromIndexes . length ) { for ( const subColumn of entityFieldMetaOptions . excludeFromIndexes ) { excludeFromIndexes . push ( `${ subColumn }` ) ; } } } decoratorMeta . addEntityMeta ( target , { kind : options . kind || target . name , namespace : options . namespace === "" ? undefined : options . namespace , excludeFromIndexes , enumerable : options . enumerable || false , } ) ; } ; }