implement custom typeorm naming strategy

This commit is contained in:
Philipinho
2024-03-03 00:15:53 +00:00
parent 3d90fc01ad
commit 7afd893fa1
2 changed files with 63 additions and 0 deletions

View File

@ -0,0 +1,61 @@
import { DefaultNamingStrategy, Table } from 'typeorm';
export class NamingStrategy extends DefaultNamingStrategy {
primaryKeyName(tableOrName: Table | string, columnNames: string[]): string {
const tableName = this.normalizeTableName(tableOrName);
return `pk_${tableName}_${columnNames.join('_')}`;
}
indexName(
tableOrName: Table | string,
columnNames: string[],
where?: string,
): string {
const tableName = this.normalizeTableName(tableOrName);
let name = `${tableName}_${columnNames.join('_')}`;
if (where) name += '_' + where;
return `idx_${name}`;
}
uniqueConstraintName(
tableOrName: Table | string,
columnNames: string[],
): string {
const tableName = this.normalizeTableName(tableOrName);
return `uq_${tableName}_${columnNames.join('_')}`;
}
foreignKeyName(
tableOrName: Table | string,
columnNames: string[],
_referencedTablePath?: string,
_referencedColumnNames?: string[],
): string {
const tableName = this.normalizeTableName(tableOrName);
const targetTable = this.normalizeTableName(_referencedTablePath);
const name = `${tableName}_${targetTable}_${columnNames.join('_')}`;
return `fk_${name}`;
}
relationConstraintName(
tableOrName: Table | string,
columnNames: string[],
where?: string,
): string {
const tableName = this.normalizeTableName(tableOrName);
let name = `${tableName}_${columnNames.join('_')}`;
if (where) name += '_' + where;
return `rel_${name}`;
}
normalizeTableName(tableOrName: Table | string): string {
const tableName = this.getTableName(tableOrName);
return tableName.replace('.', '_');
}
}

View File

@ -1,5 +1,6 @@
import { DataSource } from 'typeorm';
import * as dotenv from 'dotenv';
import { NamingStrategy } from './naming-strategy';
dotenv.config();
export const AppDataSource: DataSource = new DataSource({
type: 'postgres',
@ -10,5 +11,6 @@ export const AppDataSource: DataSource = new DataSource({
migrations: ['src/**/migrations/*.{ts,js}'],
subscribers: [],
synchronize: false,
//namingStrategy: new NamingStrategy(),
logging: process.env.NODE_ENV === 'development',
});