TypeORM和Postgres竞争的命名样式

时间:2019-03-19 19:46:38

标签: postgresql typeorm

我们正在使用TypeORM和Postgresql,我对命名约定感到好奇。

鉴于存在与用于Javascript的完美样式不同的完全合适的数据库样式和命名约定,是强迫数据库使用代码约定或强制代码使用数据库约定的更好实践,或翻译所有内容?

例如:

通常使用Joe Celko's SQL Programming Style中定义的SQl样式作为数据库。提倡使用snake_case作为列名。

使用JavaScript和typeorm上的所有文档进行编程时,通常会在camelCase中命名变量。

因此,当这两个世界发生冲突时,最好的做法是将一个世界强加给另一个世界,或者翻译定义中的每个多字实体进行映射。

这实际上不是如何做到这一点的问题,而是如果有一种常见的方法来实现。

代表用户ID的列的三种可能性是:

1: Translate everything
@Column( { name: user_id } )
userId: number;

2: Use the database convention in the code
@Column()
user_id: number;

3: Use the coding convention in the database
@Column()
userId: number

1 个答案:

答案 0 :(得分:2)

通过调整ormconfig.js以支持Typeorm Naming Strategies软件包,可以在TypeOrm中同时支持这两种方法。这将使您在代码内具有编码约定,而在数据库内具有数据库命名约定。

可以通过以下方式设置

npm i --save typeorm-naming-strategies

然后在ormconfig.js中添加以下行:

const SnakeNamingStrategy = require('typeorm-naming-strategies')
  .SnakeNamingStrategy;

module.exports = {
    name: 'development',
    type: 'postgres',
    host: 'localhost',
    port: 5432,
   ...
   namingStrategy: new SnakeNamingStrategy(),
}

在Postgres中命名列时,TypeOrm现在将遵循snake_case约定