【问题标题】:Typeorm deployment on HerokuHeroku 上的 Typeorm 部署
【发布时间】:2020-06-29 04:49:51
【问题描述】:
{
  "name": "default",
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "password": "PG_PASSWORD",
  "database": "postgres",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entity/*.*"]
}

这是我的ormconfig.json。所以 Heroku 显然在我的数据库上给了我一个连接被拒绝的错误。我设置了一个 Postgres 插件,现在我的设置页面中有一个 DATABASE_URL 环境变量。如果我添加一个DATABASE_URL env,

我的问题是如何让我的 ormconfig 获取该环境变量?因为现在主机和端口以及 un/pw 等都是独立的,我需要将它们合并到我的 ormconfig 中的一个配置选项中。

【问题讨论】:

  • 你能试试"my_url": "${DATABASE_URL}"吗?
  • @donquih0te 这是一个 json 文件。环境变量在那里不起作用。此外,他的问题是如何将$DATABASE_URL 拆分为其组件。
  • 您能指定您使用的编程语言吗? Python? JavaScript?重击?
  • TypeScript 是我使用的语言

标签: postgresql heroku deployment backend typeorm


【解决方案1】:

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

  1. 您可以使用环境变量 DATABASE_URL 在 typescript 中创建 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');
});
  1. 在 heroku 上,您可以在插件设置中获取数据库凭据,当然也可以从 url 获取。因此,您可以使用这些凭据为 heroku 编写一个 ormconfig.json。
{
  "name": "default",
  "type": "postgres",
  "url: "postgres://username:password@hostname:5432/databasename"
  "synchronize": false,
  "logging": true,
  "entities": ["src/entity/*.*"]
}

我更喜欢选项一,因为 url 可以在 heroku 上更改,您不必在代码/配置文件中做任何事情。

【讨论】:

  • 当我使用选项 2 时出现错误:自签名证书。知道吗?
猜你喜欢
  • 2020-10-18
  • 2017-06-27
  • 2017-01-19
  • 1970-01-01
  • 2015-03-28
  • 2017-01-21
  • 2020-08-07
  • 2016-11-25
  • 2018-12-28
相关资源
最近更新 更多