From 3cdbbaff11b18bcc5e6fd29fd182e2bd66b14f17 Mon Sep 17 00:00:00 2001 From: doug-martin Date: Thu, 16 Jul 2020 23:04:40 -0500 Subject: [PATCH] fix(typeorm): Ensure record is entity instance when saving * Fixes #380 --- .../src/services/typeorm-query.service.ts | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/query-typeorm/src/services/typeorm-query.service.ts b/packages/query-typeorm/src/services/typeorm-query.service.ts index d88fa1dd3..135cfa9cb 100644 --- a/packages/query-typeorm/src/services/typeorm-query.service.ts +++ b/packages/query-typeorm/src/services/typeorm-query.service.ts @@ -123,8 +123,8 @@ export class TypeOrmQueryService extends RelationQueryService im * @param record - The entity to create. */ async createOne>(record: C): Promise { - await this.ensureEntityDoesNotExist(record); - return this.repo.save(record); + const entity = await this.ensureIsEntityAndDoesNotExist(record); + return this.repo.save(entity); } /** @@ -140,8 +140,8 @@ export class TypeOrmQueryService extends RelationQueryService im * @param records - The entities to create. */ async createMany>(records: C[]): Promise { - await Promise.all(records.map((r) => this.ensureEntityDoesNotExist(r))); - return this.repo.save(records); + const entities = await Promise.all(records.map((r) => this.ensureIsEntityAndDoesNotExist(r))); + return this.repo.save(entities); } /** @@ -260,22 +260,30 @@ export class TypeOrmQueryService extends RelationQueryService im return { updatedCount: result.affected || 0 }; } - async ensureEntityDoesNotExist(e: DeepPartial): Promise { - if (this.repo.hasId((e as unknown) as Entity)) { - const found = await this.repo.findOne(this.repo.getId((e as unknown) as Entity)); + private async ensureIsEntityAndDoesNotExist(e: DeepPartial): Promise { + if (!(e instanceof this.EntityClass)) { + return this.ensureEntityDoesNotExist(this.repo.create(e)); + } + return this.ensureEntityDoesNotExist(e); + } + + private async ensureEntityDoesNotExist(e: Entity): Promise { + if (this.repo.hasId(e)) { + const found = await this.repo.findOne(this.repo.getId(e)); if (found) { throw new Error('Entity already exists'); } } + return e; } - ensureIdIsNotPresent(e: DeepPartial): void { + private ensureIdIsNotPresent(e: DeepPartial): void { if (this.repo.hasId((e as unknown) as Entity)) { throw new Error('Id cannot be specified when updating'); } } - ensureSoftDeleteEnabled(): void { + private ensureSoftDeleteEnabled(): void { if (!this.useSoftDelete) { throw new MethodNotAllowedException(`Restore not allowed for non soft deleted entity ${this.EntityClass.name}.`); }