Commit 5ea314ec authored by nanahira's avatar nanahira

rename some entity abstract functions

parent 5d02661a
...@@ -8,7 +8,7 @@ export interface DeletionWise { ...@@ -8,7 +8,7 @@ export interface DeletionWise {
export interface ImportWise { export interface ImportWise {
isValidInCreation(): string | undefined; isValidInCreation(): string | undefined;
prepareForSaving(): Promise<void>; beforeSaving(): Promise<void>;
afterSaving(): void; afterSaving(): void;
} }
...@@ -28,19 +28,15 @@ export class TimeBase ...@@ -28,19 +28,15 @@ export class TimeBase
@NotColumn() @NotColumn()
deleteTime: Date; deleteTime: Date;
toObject() {
return JSON.parse(JSON.stringify(this));
}
isValidInCreation(): string | undefined { isValidInCreation(): string | undefined {
return; return;
} }
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
async prepareForSaving(): Promise<void> {} async beforeSaving(): Promise<void> {}
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
afterSaving() {} async afterSaving(): Promise<void> {}
} }
export const TimeBaseFields: (keyof TimeBase)[] = [ export const TimeBaseFields: (keyof TimeBase)[] = [
......
...@@ -69,7 +69,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -69,7 +69,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
this.extraGetQuery = crudOptions.extraGetQuery || ((qb) => {}); this.extraGetQuery = crudOptions.extraGetQuery || ((qb) => {});
} }
async batchCreate( async _batchCreate(
ents: T[], ents: T[],
beforeCreate?: (repo: Repository<T>) => Promise<void>, beforeCreate?: (repo: Repository<T>) => Promise<void>,
skipErrors = false, skipErrors = false,
...@@ -133,13 +133,20 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -133,13 +133,20 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
this.log.error( this.log.error(
`Failed to create entity ${JSON.stringify(ents)}: ${e.toString()}`, `Failed to create entity ${JSON.stringify(ents)}: ${e.toString()}`,
); );
throw new BlankReturnMessageDto(500, 'internal error').toException(); throw new BlankReturnMessageDto(500, 'Internal error').toException();
} }
}); });
return result; return result;
} }
async create(ent: T, beforeCreate?: (repo: Repository<T>) => Promise<void>) { async create(ent: T, beforeCreate?: (repo: Repository<T>) => Promise<void>) {
if (!ent) {
throw new BlankReturnMessageDto(400, 'Invalid entity').toException();
}
const invalidReason = ent.isValidInCreation();
if (invalidReason) {
throw new BlankReturnMessageDto(400, invalidReason).toException();
}
const savedEnt = await this.repo.manager.transaction(async (mdb) => { const savedEnt = await this.repo.manager.transaction(async (mdb) => {
const repo = mdb.getRepository(this.entityClass); const repo = mdb.getRepository(this.entityClass);
if (ent.id != null) { if (ent.id != null) {
...@@ -162,13 +169,15 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -162,13 +169,15 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
if (beforeCreate) { if (beforeCreate) {
await beforeCreate(repo); await beforeCreate(repo);
} }
await ent.beforeSaving();
try { try {
return await repo.save(ent as DeepPartial<T>); const savedEnt = await repo.save(ent as DeepPartial<T>);
await savedEnt.afterSaving();
} catch (e) { } catch (e) {
this.log.error( this.log.error(
`Failed to create entity ${JSON.stringify(ent)}: ${e.toString()}`, `Failed to create entity ${JSON.stringify(ent)}: ${e.toString()}`,
); );
throw new BlankReturnMessageDto(500, 'internal error').toException(); throw new BlankReturnMessageDto(500, 'Internal error').toException();
} }
}); });
return new this.entityReturnMessageDto(201, 'success', savedEnt); return new this.entityReturnMessageDto(201, 'success', savedEnt);
...@@ -178,7 +187,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -178,7 +187,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
return camelCase(this.entityName); return camelCase(this.entityName);
} }
applyRelationToQuery(qb: SelectQueryBuilder<T>, relation: RelationDef) { _applyRelationToQuery(qb: SelectQueryBuilder<T>, relation: RelationDef) {
const { name } = relation; const { name } = relation;
const relationUnit = name.split('.'); const relationUnit = name.split('.');
const base = const base =
...@@ -193,12 +202,12 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -193,12 +202,12 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
qb[methodName](`${base}.${property}`, properyAlias); qb[methodName](`${base}.${property}`, properyAlias);
} }
applyRelationsToQuery(qb: SelectQueryBuilder<T>) { _applyRelationsToQuery(qb: SelectQueryBuilder<T>) {
for (const relation of this.entityRelations) { for (const relation of this.entityRelations) {
if (typeof relation === 'string') { if (typeof relation === 'string') {
this.applyRelationToQuery(qb, { name: relation }); this._applyRelationToQuery(qb, { name: relation });
} else { } else {
this.applyRelationToQuery(qb, relation); this._applyRelationToQuery(qb, relation);
} }
} }
} }
...@@ -215,7 +224,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -215,7 +224,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
const query = this.queryBuilder() const query = this.queryBuilder()
.where(`${this.entityAliasName}.id = :id`, { id }) .where(`${this.entityAliasName}.id = :id`, { id })
.take(1); .take(1);
this.applyRelationsToQuery(query); this._applyRelationsToQuery(query);
this.extraGetQuery(query); this.extraGetQuery(query);
extraQuery(query); extraQuery(query);
query.take(1); query.take(1);
...@@ -229,7 +238,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -229,7 +238,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
',', ',',
)}: ${e.toString()}`, )}: ${e.toString()}`,
); );
throw new BlankReturnMessageDto(500, 'internal error').toException(); throw new BlankReturnMessageDto(500, 'Internal error').toException();
} }
if (!ent) { if (!ent) {
throw new BlankReturnMessageDto( throw new BlankReturnMessageDto(
...@@ -251,7 +260,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -251,7 +260,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
Object.assign(newEnt, ent); Object.assign(newEnt, ent);
newEnt.applyQuery(query, this.entityAliasName); newEnt.applyQuery(query, this.entityAliasName);
} }
this.applyRelationsToQuery(query); this._applyRelationsToQuery(query);
this.extraGetQuery(query); this.extraGetQuery(query);
extraQuery(query); extraQuery(query);
try { try {
...@@ -270,7 +279,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -270,7 +279,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
ent, ent,
)} with SQL ${sql} param ${params.join(',')}: ${e.toString()}`, )} with SQL ${sql} param ${params.join(',')}: ${e.toString()}`,
); );
throw new BlankReturnMessageDto(500, 'internal error').toException(); throw new BlankReturnMessageDto(500, 'Internal error').toException();
} }
} }
...@@ -294,7 +303,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -294,7 +303,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
entPart, entPart,
)}: ${e.toString()}`, )}: ${e.toString()}`,
); );
throw new BlankReturnMessageDto(500, 'internal error').toException(); throw new BlankReturnMessageDto(500, 'Internal error').toException();
} }
if (!result.affected) { if (!result.affected) {
throw new BlankReturnMessageDto( throw new BlankReturnMessageDto(
...@@ -317,7 +326,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -317,7 +326,7 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
: this.repo.softDelete(searchCond)); : this.repo.softDelete(searchCond));
} catch (e) { } catch (e) {
this.log.error(`Failed to delete entity ID ${id}: ${e.toString()}`); this.log.error(`Failed to delete entity ID ${id}: ${e.toString()}`);
throw new BlankReturnMessageDto(500, 'internal error').toException(); throw new BlankReturnMessageDto(500, 'Internal error').toException();
} }
if (!result.affected) { if (!result.affected) {
throw new BlankReturnMessageDto( throw new BlankReturnMessageDto(
...@@ -351,13 +360,9 @@ export class CrudBase<T extends ValidCrudEntity<T>> { ...@@ -351,13 +360,9 @@ export class CrudBase<T extends ValidCrudEntity<T>> {
const remainingEnts = ents.filter( const remainingEnts = ents.filter(
(ent) => !invalidResults.find((result) => result.entry === ent), (ent) => !invalidResults.find((result) => result.entry === ent),
); );
await Promise.all(remainingEnts.map((ent) => ent.prepareForSaving())); await Promise.all(remainingEnts.map((ent) => ent.beforeSaving()));
const data = await this.batchCreate(remainingEnts, undefined, true); const data = await this._batchCreate(remainingEnts, undefined, true);
data.results.forEach((e) => { await Promise.all(data.results.map((e) => e.afterSaving()));
if (e.afterSaving) {
e.afterSaving();
}
});
const results = [ const results = [
...invalidResults, ...invalidResults,
...data.skipped, ...data.skipped,
......
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