Commit ebe91c82 authored by nanahira's avatar nanahira

create existing logic

parent 91960695
Pipeline #6880 passed with stages
in 1 minute and 35 seconds
...@@ -34,15 +34,35 @@ export class CrudBase< ...@@ -34,15 +34,35 @@ export class CrudBase<
} }
async create(ent: T) { async create(ent: T) {
try { const savedEnt = await this.repo.manager.transaction(async (mdb) => {
const savedEntity = await this.repo.save(ent); const repo = mdb.getRepository(this.entityClass);
return new ReturnMessageDto(201, 'success', savedEntity); if (ent.id != null) {
} catch (e) { const existingEnt = await repo.findOne({
this.error( where: { id: ent.id },
`Failed to create entity ${JSON.stringify(ent)}: ${e.toString()}`, take: 1,
); select: ['id', 'isDeleted'],
throw new BlankReturnMessageDto(500, 'internal error').toException(); });
} if (existingEnt) {
if (existingEnt.isDeleted) {
await repo.delete({ id: ent.id });
} else {
throw new BlankReturnMessageDto(
404,
'already exists',
).toException();
}
}
}
try {
return await repo.save(ent);
} catch (e) {
this.error(
`Failed to create entity ${JSON.stringify(ent)}: ${e.toString()}`,
);
throw new BlankReturnMessageDto(500, 'internal error').toException();
}
});
return new ReturnMessageDto(201, 'success', savedEnt);
} }
protected get entityAliasName() { protected get entityAliasName() {
...@@ -76,7 +96,8 @@ export class CrudBase< ...@@ -76,7 +96,8 @@ export class CrudBase<
async findOne(id: EntityId<T>) { async findOne(id: EntityId<T>) {
const query = this.queryBuilder() const query = this.queryBuilder()
.where(`${this.entityAliasName}.id = :id`, { id }) .where(`${this.entityAliasName}.id = :id`, { id })
.andWhere(`${this.entityAliasName}.isDeleted = false`); .andWhere(`${this.entityAliasName}.isDeleted = false`)
.take(1);
this.applyRelationsToQuery(query); this.applyRelationsToQuery(query);
this.extraGetQuery(query); this.extraGetQuery(query);
try { try {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment