{"version":3,"file":"repo.cjs","sources":["../src/util/exceptions.ts","../src/mongoose.repository.ts","../src/util/schema.ts"],"sourcesContent":["export class NotFoundException extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n\nexport class UniquenessViolationException extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n\nexport class IllegalArgumentException extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n\nexport class UndefinedConstructorException extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n","import { Repository } from './repository';\nimport { Optional } from 'typescript-optional';\nimport mongoose, {\n  Connection,\n  HydratedDocument,\n  Model,\n  Schema,\n  UpdateQuery,\n} from 'mongoose';\nimport { Entity } from './util/entity';\nimport {\n  IllegalArgumentException,\n  NotFoundException,\n  UndefinedConstructorException,\n  UniquenessViolationException,\n} from './util/exceptions';\n\ntype Constructor<T> = new (...args: any) => T;\n\ninterface ConstructorMap<T> {\n  [index: string]: { type: Constructor<T>; schema: Schema };\n}\n\ntype PartialEntityWithIdAndOptionalDiscriminatorKey<T> = { id: string } & {\n  __t?: string;\n} & Partial<T>;\n\ntype PartialEntityWithId<T> = { id: string } & Partial<T>;\n\nexport abstract class MongooseRepository<T extends Entity & UpdateQuery<T>>\n  implements Repository<T>\n{\n  protected readonly entityModel: Model<T>;\n\n  protected constructor(\n    private readonly entityConstructorMap: ConstructorMap<T>,\n    private readonly connection?: Connection,\n  ) {\n    this.entityModel = this.createEntityModel(entityConstructorMap, connection);\n  }\n\n  async deleteById(id: string): Promise<boolean> {\n    if (!id) throw new IllegalArgumentException('The given ID must be valid');\n    const isDeleted = await this.entityModel.findByIdAndDelete(id);\n    return !!isDeleted;\n  }\n\n  async findAll<S extends T>(filters?: any, sortBy?: any): Promise<S[]> {\n    return this.entityModel\n      .find(filters)\n      .sort(sortBy)\n      .exec()\n      .then((documents) =>\n        documents.map((document) => this.instantiateFrom(document) as S),\n      );\n  }\n\n  async findById<S extends T>(id: string): Promise<Optional<S>> {\n    if (!id) throw new IllegalArgumentException('The given ID must be valid');\n    return this.entityModel\n      .findById(id)\n      .exec()\n      .then((document) =>\n        Optional.ofNullable(this.instantiateFrom(document) as S),\n      );\n  }\n\n  async save<S extends T>(\n    entity: S | PartialEntityWithIdAndOptionalDiscriminatorKey<S>,\n  ): Promise<S> {\n    if (!entity)\n      throw new IllegalArgumentException('The given entity must be valid');\n    let document;\n    if (!entity.id) {\n      document = await this.insert(entity as S);\n    } else {\n      document = await this.update(\n        entity as PartialEntityWithIdAndOptionalDiscriminatorKey<S>,\n      );\n    }\n    if (document) return this.instantiateFrom(document) as S;\n    throw new NotFoundException(\n      `There is no document matching the given ID ${entity.id}. New entities cannot not specify an ID`,\n    );\n  }\n\n  protected instantiateFrom<S extends T>(\n    document: HydratedDocument<S> | null,\n  ): S | null {\n    if (!document) return null;\n    const discriminatorType = document.get('__t');\n    const entityConstructor =\n      this.entityConstructorMap[discriminatorType ?? 'Default'].type;\n    if (entityConstructor) {\n      return new entityConstructor(document.toObject()) as S;\n    }\n    throw new UndefinedConstructorException(\n      `There is no registered instance constructor for the document with ID ${document.id}`,\n    );\n  }\n\n  private createEntityModel<T>(\n    entityConstructorMap: ConstructorMap<T>,\n    connection?: Connection,\n  ) {\n    let entityModel;\n    const supertypeName = entityConstructorMap['Default'].type.name;\n    const supertypeSchema = entityConstructorMap['Default'].schema;\n    if (connection) {\n      entityModel = connection.model<T>(supertypeName, supertypeSchema);\n    } else {\n      entityModel = mongoose.model<T>(supertypeName, supertypeSchema);\n    }\n    for (const subtypeName in entityConstructorMap) {\n      if (!(subtypeName === 'Default')) {\n        const subtypeSchema = entityConstructorMap[subtypeName].schema;\n        entityModel.discriminator(subtypeName, subtypeSchema);\n      }\n    }\n    return entityModel;\n  }\n\n  private async insert<S extends T>(entity: S): Promise<HydratedDocument<S>> {\n    try {\n      this.setDiscriminatorKeyOn(entity);\n      return (await this.entityModel.create(\n        entity,\n      )) as unknown as HydratedDocument<S>;\n    } catch (error) {\n      if (error.message.includes('duplicate key error')) {\n        throw new UniquenessViolationException(\n          `The given entity with ID ${entity.id} includes a field which value is expected to be unique`,\n        );\n      }\n      throw error;\n    }\n  }\n\n  private setDiscriminatorKeyOn<S extends T>(\n    entity: S | PartialEntityWithIdAndOptionalDiscriminatorKey<S>,\n  ): void {\n    const entityClassName = entity['constructor']['name'];\n    const entitySpecifiesDiscriminatorKey = '__t' in entity;\n    const entityIsSupertype =\n      entityClassName !== this.entityConstructorMap['Default'].type.name;\n    if (!entitySpecifiesDiscriminatorKey && entityIsSupertype) {\n      entity['__t'] = entityClassName;\n    }\n  }\n\n  private async update<S extends T>(\n    entity: PartialEntityWithId<S>,\n  ): Promise<HydratedDocument<S> | null> {\n    const document = await this.entityModel.findById<HydratedDocument<S>>(\n      entity.id,\n    );\n    if (document) {\n      document.set(entity);\n      document.isNew = false;\n      return (await document.save()) as HydratedDocument<S>;\n    }\n    return null;\n  }\n}\n","import mongoose from 'mongoose';\n\nexport const BaseSchema = new mongoose.Schema(\n  {},\n  {\n    // required to deserialize Entity objects\n    toObject: {\n      transform: (document, result) => {\n        result.id = document.id;\n        delete result._id;\n      },\n    },\n  },\n);\n\nexport function extendSchema(schema: any, definition: any, options?: any) {\n  return new mongoose.Schema(\n    { ...schema.obj, ...definition },\n    { ...schema.options, ...options },\n  );\n}\n"],"names":["NotFoundException","_Error","message","call","this","_inheritsLoose","_wrapNativeSuper","Error","UniquenessViolationException","_Error2","IllegalArgumentException","_Error3","UndefinedConstructorException","_Error4","MongooseRepository","entityConstructorMap","connection","entityModel","createEntityModel","_proto","prototype","deleteById","id","Promise","resolve","findByIdAndDelete","then","isDeleted","e","reject","findAll","filters","sortBy","_this2","find","sort","exec","documents","map","document","instantiateFrom","findById","_this3","Optional","ofNullable","save","entity","_temp2","_this4","_temp","update","_this4$update","insert","_this4$insert","discriminatorType","get","entityConstructor","type","toObject","supertypeName","name","supertypeSchema","schema","subtypeName","model","mongoose","discriminator","_this5","setDiscriminatorKeyOn","create","_catch","error","includes","entityClassName","_exit","_temp3","set","isNew","_await$document$save","_result","BaseSchema","Schema","transform","result","_id","definition","options","_extends","obj"],"mappings":"ynDAAa,IAAAA,eAAkBC,SAAAA,GAC7B,SAAAD,EAAYE,GAAe,OACzBD,EAAAE,KAAMD,KAAAA,IAAQE,IAChB,CAAC,OAH4BC,EAAAL,EAAAC,GAG5BD,CAAA,CAH4BC,cAG5BK,EAHoCC,QAM1BC,eAA6BC,SAAAA,GACxC,SAAAD,EAAYN,GAAe,OACzBO,EAAAN,KAAMD,KAAAA,IAAQE,IAChB,CAAC,OAHuCC,EAAAG,EAAAC,GAGvCD,CAAA,CAHuCC,cAGvCH,EAH+CC,QAMrCG,eAAyBC,SAAAA,GACpC,SAAAD,EAAYR,GAAe,OACzBS,EAAAR,KAAMD,KAAAA,IAAQE,IAChB,CAAC,OAHmCC,EAAAK,EAAAC,GAGnCD,CAAA,CAHmCC,cAGnCL,EAH2CC,QAMjCK,eAA8BC,SAAAA,GACzC,SAAAD,EAAYV,GACV,OAAAW,EAAAV,KAAAC,KAAMF,IACRE,IAAA,CAAC,OAHwCC,EAAAO,EAAAC,GAGxCD,CAAA,CAHwCC,cAGxCP,EAHgDC,QCW7BO,eAKpB,WAAA,SAAAA,EACmBC,EACAC,GADAD,KAAAA,0BACAC,EAAAA,KAAAA,uBAJAC,iBAAW,EAGXb,KAAoBW,qBAApBA,EACAX,KAAUY,WAAVA,EAEjBZ,KAAKa,YAAcb,KAAKc,kBAAkBH,EAAsBC,EAClE,CAAC,IAAAG,EAAAL,EAAAM,UA2HA,OA3HAD,EAEKE,WAAU,SAACC,OACf,IAAKA,EAAI,MAAM,IAAIZ,EAAyB,8BAA8B,OAAAa,QAAAC,QAClDpB,KAAKa,YAAYQ,kBAAkBH,IAAGI,KAAxDC,SAAAA,GACN,QAASA,CAAU,EACrB,CAAC,MAAAC,GAAA,OAAAL,QAAAM,OAAAD,EAAAT,CAAAA,EAAAA,EAEKW,QAAOA,SAAcC,EAAeC,GAAY,IAAA,IAA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