Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Naming Strategy for Pluralized Tables and Singular Columns #43

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,8 @@
},
"peerDependencies": {
"typeorm": "^0.2.0 || ^0.3.0"
},
"dependencies": {
"pluralize": "^8.0.0"
}
}
17 changes: 9 additions & 8 deletions src/snake-naming.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
// Credits to @recurrence
// https://gist.github.com/recurrence/b6a4cb04a8ddf42eda4e4be520921bd2

import pluralize from 'pluralize';
import { DefaultNamingStrategy, NamingStrategyInterface } from 'typeorm';
import { snakeCase } from 'typeorm/util/StringUtils';

export class SnakeNamingStrategy
extends DefaultNamingStrategy
implements NamingStrategyInterface {
tableName(className: string, customName: string): string {
return customName ? customName : snakeCase(className);
return pluralize(customName ? customName : snakeCase(className));
}

columnName(
Expand All @@ -27,7 +28,9 @@ export class SnakeNamingStrategy
}

joinColumnName(relationName: string, referencedColumnName: string): string {
return snakeCase(relationName + '_' + referencedColumnName);
return snakeCase(
pluralize.singular(relationName) + '_' + referencedColumnName,
);
}

joinTableName(
Expand All @@ -37,11 +40,7 @@ export class SnakeNamingStrategy
secondPropertyName: string,
): string {
return snakeCase(
firstTableName +
'_' +
firstPropertyName.replace(/\./gi, '_') +
'_' +
secondTableName,
firstTableName + '_' + secondTableName.replace(/\./gi, '_'),
);
}

Expand All @@ -51,7 +50,9 @@ export class SnakeNamingStrategy
columnName?: string,
): string {
return snakeCase(
tableName + '_' + (columnName ? columnName : propertyName),
pluralize.singular(tableName) +
'_' +
(columnName ? columnName : propertyName),
);
}

Expand Down