在 Heroku 上部署 Typeorm

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

你(至少)有两种可能性。

  1. 您可以使用环境变量 DATABASE_URL 在打字稿中创建 ConnectionOptions。如果您有 url,则不需要主机、用户名、端口、密码、数据库,实际上您应该删除它们,因为它们会覆盖您的 url 参数。请参见此处:https : //typeorm.io/#/connection-options/postgres--cockroachdb-connection-options

    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)
  1. 在 heroku 上,您可以在插件设置中或当然从 url 中获取数据库凭据。因此,您可以使用这些凭据为 heroku 编写一个 ormconfig.json。
{
  "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 上改变,你不必在你的代码/配置文件中做任何事情。