fix(API): reduce code duplication between DB entities (#4351)
This commit is contained in:
committed by
GitHub
parent
5eb1eb88e4
commit
5eebd91ba7
39
packages/cli/src/databases/entities/AbstractEntity.ts
Normal file
39
packages/cli/src/databases/entities/AbstractEntity.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { BeforeUpdate, CreateDateColumn, UpdateDateColumn } from 'typeorm';
|
||||
import { IsDate, IsOptional } from 'class-validator';
|
||||
import config from '../../../config';
|
||||
|
||||
const dbType = config.getEnv('database.type');
|
||||
|
||||
const timestampSyntax = {
|
||||
sqlite: `STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')`,
|
||||
postgresdb: 'CURRENT_TIMESTAMP(3)',
|
||||
mysqldb: 'CURRENT_TIMESTAMP(3)',
|
||||
mariadb: 'CURRENT_TIMESTAMP(3)',
|
||||
}[dbType];
|
||||
|
||||
export const jsonColumnType = dbType === 'sqlite' ? 'simple-json' : 'json';
|
||||
export const datetimeColumnType = dbType === 'postgresdb' ? 'timestamptz' : 'datetime';
|
||||
|
||||
export abstract class AbstractEntity {
|
||||
@CreateDateColumn({
|
||||
precision: 3,
|
||||
default: () => timestampSyntax,
|
||||
})
|
||||
@IsOptional() // ignored by validation because set at DB level
|
||||
@IsDate()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({
|
||||
precision: 3,
|
||||
default: () => timestampSyntax,
|
||||
onUpdate: timestampSyntax,
|
||||
})
|
||||
@IsOptional() // ignored by validation because set at DB level
|
||||
@IsDate()
|
||||
updatedAt: Date;
|
||||
|
||||
@BeforeUpdate()
|
||||
setUpdateDate(): void {
|
||||
this.updatedAt = new Date();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user