gpt4 book ai didi

node.js - 带有 .env 变量的 typeorm 配置

转载 作者:行者123 更新时间:2023-12-04 02:35:32 25 4
gpt4 key购买 nike

我有这个 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 中使用我的环境变量

最佳答案

有一个很好的 documentation
如果你想深入到源代码 - 还有一类ConnectionOptionReader,这是寻找文件ormconfig(扩展envjscjstsjsonymlyamlxml)或文件.env。有关更多详细信息,请参阅 load 函数。
1 所以最简单的方法是在您的 .env 文件中添加一行,如下所示:

TYPEORM_URL=postgres://user:pass@host:port/dbname
或者使用这个 sample 。 TypeORM 将使用 dotenv 解析 .env 文件。
Here 你可以找到所有可用的环境变量。
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"
}
};
另一个 example

关于node.js - 带有 .env 变量的 typeorm 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62143322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com