Jim*_*ide 2 deployment postgresql backend heroku typeorm
{
"name": "default",
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "postgres",
"password": "PG_PASSWORD",
"database": "postgres",
"synchronize": true,
"logging": true,
"entities": ["src/entity/*.*"]
}
Run Code Online (Sandbox Code Playgroud)
这是我的ormconfig.json。所以 Heroku 显然在我的数据库上给了我一个连接被拒绝的错误。我设置了一个 Postgres 插件,现在我的设置页面中有一个 DATABASE_URL 环境变量。如果我添加一个环境DATABASE_URL,
我的问题是如何让我的 ormconfig 接受那个 env 变量?因为现在主机和端口以及 un/pw 等都是独立的,我需要将它们整合到我的 ormconfig 中的一个配置选项中。
小智 5
你(至少)有两种可能性。
url - 执行连接的连接 url。请注意,其他连接选项将覆盖从 url 设置的参数。
例如像这样:
import { getConnectionOptions, ConnectionOptions } from 'typeorm';
import dotenv from 'dotenv';
dotenv.config();
const getOptions = async () => {
let connectionOptions: ConnectionOptions;
connectionOptions = {
type: 'postgres',
synchronize: false,
logging: false,
extra: {
ssl: true,
},
entities: ['dist/entity/*.*'],
};
if (process.env.DATABASE_URL) {
Object.assign(connectionOptions, { url: process.env.DATABASE_URL });
} else {
// gets your default configuration
// you could get a specific config by name getConnectionOptions('production')
// or getConnectionOptions(process.env.NODE_ENV)
connectionOptions = await getConnectionOptions();
}
return connectionOptions;
};
const connect2Database = async (): Promise<void> => {
const typeormconfig = await getOptions();
await createConnection(typeormconfig);
};
connect2Database().then(async () => {
console.log('Connected to database');
});
Run Code Online (Sandbox Code Playgroud)
{
"name": "default",
"type": "postgres",
"url: "postgres://username:password@hostname:5432/databasename"
"synchronize": false,
"logging": true,
"entities": ["src/entity/*.*"]
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢选项一,因为 url 可以在 heroku 上改变,你不必在你的代码/配置文件中做任何事情。
| 归档时间: |
|
| 查看次数: |
3525 次 |
| 最近记录: |