[英]typeorm config with .env variables
我有这个 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"
}
}
并拥有这个环境:
SERVER_PORT=4000
DB_HOST=db-pg
DB_PORT=5432
DB_USER=spirit
DB_PASS=api
DB_NAME=emasa_ci
但是.env 在.json 中不起作用,所以我不知道如何在我的配置 orm 中使用我的环境变量
有一个很好的文档。 If you want to dig into the source code - there is a class ConnectionOptionReader, which is looking for file ormconfig
(with extensions env
, js
, cjs
, ts
, json
, yml
, yaml
, xml
) or for file .env
. 有关详细信息,请参阅负载function。
1 因此,最简单的方法是在.env
文件中添加一行,如下所示:
TYPEORM_URL=postgres://user:pass@host:port/dbname
或使用此示例。 TypeORM 将使用dotenv解析.env 文件。
在这里您可以找到所有可用的环境变量。
2 如果你在 TypeORM 初始化之前阅读了你的.env
文件,你已经可以使用你的 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"
}
};
另一个例子
您可以隐藏ormconfig.json
并将您的秘密直接放在那里,反之亦然,从您的.env
文件加载 TypeORM 的配置。 您需要将它们分开是否有确切的原因? 如果是,那么我们可以制定解决方案。
由于ormconfig 已弃用,我建议使用另一种方法使用 TypeORM 数据源。
我正在使用 Heroku 来部署我的服务器,因此我创建了一个环境文件,其中包含与在 Heroku Dynos 中创建的相同变量,名为.development.env
:
DATABASE_URL="postgres://user:password@localhost:5432/main"
请注意,您可以将此文件放在项目树中的任何位置。
然后我创建了一个数据源文件:
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;
这样,您可以在您的环境中存储您的数据库连接设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.