Skip to content

Instantly share code, notes, and snippets.

@x47188
Last active August 19, 2021 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x47188/fed66c35189a5265ab2948bd87cb4fbd to your computer and use it in GitHub Desktop.
Save x47188/fed66c35189a5265ab2948bd87cb4fbd to your computer and use it in GitHub Desktop.
Snake Case Naming Strategy for TypeORM
createConnection({
  [...]
  namingStrategy: new NamingStrategy()
})
import { DefaultNamingStrategy } from 'typeorm';
import { snakeCase } from 'typeorm/util/StringUtils';
export default class NamingStrategy extends DefaultNamingStrategy {
public tableName(className: string, customName: string): string {
return customName || snakeCase(className);
}
public columnName(
propertyName: string,
customName: string,
embeddedPrefixes: string[]
): string {
return `${snakeCase(embeddedPrefixes.join('_'))}${customName ||
snakeCase(propertyName)}`;
}
public relationName(propertyName: string): string {
return snakeCase(propertyName);
}
public joinColumnName(
relationName: string,
referencedColumnName: string
): string {
return snakeCase(`${relationName}_${referencedColumnName}`);
}
public joinTableName(
firstTableName: string,
secondTableName: string,
firstPropertyName: string
): string {
return snakeCase(
`${firstTableName}_${firstPropertyName.replace(
/\./gi,
'_'
)}_${secondTableName}`
);
}
public joinTableColumnName(
tableName: string,
propertyName: string,
columnName?: string
): string {
return snakeCase(`${tableName}_${columnName || propertyName}`);
}
public classTableInheritanceParentColumnName(
parentTableName: any,
parentTableIdPropertyName: any
): string {
return snakeCase(`${parentTableName}_${parentTableIdPropertyName}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment