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<
}
async create(ent: T) {
try {
const savedEntity = await this.repo.save(ent);
return new ReturnMessageDto(201, 'success', savedEntity);
} catch (e) {
this.error(
`Failed to create entity ${JSON.stringify(ent)}: ${e.toString()}`,
);
throw new BlankReturnMessageDto(500, 'internal error').toException();
}
const savedEnt = await this.repo.manager.transaction(async (mdb) => {
const repo = mdb.getRepository(this.entityClass);
if (ent.id != null) {
const existingEnt = await repo.findOne({
where: { id: ent.id },
take: 1,
select: ['id', 'isDeleted'],
});
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() {
......@@ -76,7 +96,8 @@ export class CrudBase<
async findOne(id: EntityId<T>) {
const query = this.queryBuilder()
.where(`${this.entityAliasName}.id = :id`, { id })
.andWhere(`${this.entityAliasName}.isDeleted = false`);
.andWhere(`${this.entityAliasName}.isDeleted = false`)
.take(1);
this.applyRelationsToQuery(query);
this.extraGetQuery(query);
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