带有 .env 变量的 typeorm 配置

Min*_*ing 3 node.js typeorm

我有这个 ormconfig.json:

{
  "type": "postgres",
  "host": "db-pg",
  "port": 5432,
  "username": "spirit",
  "password": "api",
  "database": "emasa_ci",
  "synchronize": true,
  "logging": false,
  "entities": ["dist/src/entity/**/*.js"],
  "migrations": ["dist/src/migration/**/*.js"],
  "subscribers": ["dist/src/subscriber/**/*.js"],
  "cli": {
    "entitiesDir": "dist/src/entity",
    "migrationsDir": "dist/src/migration",
    "subscribersDir": "dist/src/subscriber"
  }
}
Run Code Online (Sandbox Code Playgroud)

并有这个环境:

SERVER_PORT=4000
DB_HOST=db-pg
DB_PORT=5432
DB_USER=spirit
DB_PASS=api
DB_NAME=emasa_ci
Run Code Online (Sandbox Code Playgroud)

但是 .env 在 .json 中不起作用,所以我不知道我将如何在我的配置 orm 中使用我的环境变量

fri*_*nux 8

由于ormconfig 已被弃用,我建议使用 TypeORM DataSource 的另一种方法。

我正在使用 Heroku 部署我的服务器,因此我创建了一个环境文件,其中包含与 Heroku Dynos 中创建的变量相同的变量,名为.development.env

DATABASE_URL="postgres://user:password@localhost:5432/main"
Run Code Online (Sandbox Code Playgroud)

请注意,您可以将此文件放置在项目树中的任何位置。

然后我创建了一个数据源文件:

import dotenv from 'dotenv';
import { DataSource } from 'typeorm';

// Load env file
dotenv.config({ path: '../api/.development.env' });

DataSource definition
const AppDataSource = new DataSource({
  type: 'postgres',
  url: process.env.DATABASE_URL,
  logging: true,
  entities: ['../api/dist/**/*.entity.js'],
  migrations: ['./migrations/*.js'],
  subscribers: [],
});

export default AppDataSource;
Run Code Online (Sandbox Code Playgroud)

这样,您就可以在您的环境中存储数据库连接设置。


Kon*_*lov 5

有一个很好的文档。如果你想深入研究源代码 - 有一个 ConnectionOptionReader 类,它正在寻找 file ormconfig(带有扩展名env, js, cjs, ts, json, yml, yaml, xml)或 file .env。有关更多详细信息,请参阅加载功能。

1 所以最简单的方法是在你的.env文件中添加一行,像这样:

TYPEORM_URL=postgres://user:pass@host:port/dbname
Run Code Online (Sandbox Code Playgroud)

或使用此示例。TypeORM 将使用dotenv解析 .env 文件。
在这里您可以找到所有可用的环境变量。

2 如果您.env在 TypeORM 初始化之前阅读了您的文件,则您已经可以使用您的 env 变量。例如,在 Javascript 文件中,改为ormconfig.json. 只需从文件中导出这样的对象ormconfig.js

module.exports = {
    "type": "postgres",
    "host": process.env.DB_HOST,
    "port": process.env.DB_PORT,
    "username": process.env.DB_USER,
    "password": process.env.DB_PASS,
    "database": process.env.DB_NAME,
    "synchronize": true,
    "logging": false,
    "entities": ["dist/src/entity/**/*.js"],
    "migrations": ["dist/src/migration/**/*.js"],
    "subscribers": ["dist/src/subscriber/**/*.js"],
    "cli": {
      "entitiesDir": "dist/src/entity",
      "migrationsDir": "dist/src/migration",
      "subscribersDir": "dist/src/subscriber"
    }
};
Run Code Online (Sandbox Code Playgroud)

另一个例子


小智 -2

您可以隐藏ormconfig.json并直接将您的秘密放入其中,反之亦然,从您的.env文件加载 TypeORM 的配置。您需要将他们分开有确切的原因吗​​?如果是,那么我们可以制定解决方案。

  • 因为 ormconfig.json 的某些映射是特定于项目的?就像实体文件夹位置等。我不知道这个“答案”是如何获得赞成票的。将实际的潜在秘密值分离到环境文件中似乎完全合理,并且在我看来 - 甚至不需要解释为什么它更好。 (2认同)