Typeorm deployment on Heroku

Viewed 5934
{
  "name": "default",
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "password": "PG_PASSWORD",
  "database": "postgres",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entity/*.*"]
}

This is my ormconfig.json. So Heroku is obviously giving me a connection refused error on my database. I have a Postgres addon set up and I have a DATABASE_URL env variable in my setting page now. If I add a DATABASE_URL env,

my question is how do I get my ormconfig to take that env variable? Because right now host and port and un/pw, etc are all separate and I need to consolidate them down to one config option in my ormconfig.

1 Answers

You have (at least) two possibilities.

  1. You can either create the ConnectionOptions in typescript, using the environment variable DATABASE_URL. You don't need the host, username, port, password, database if you have the url, in fact you should remove them, because they overwrite parameters of your url. See here: https://typeorm.io/#/connection-options/postgres--cockroachdb-connection-options

    url - Connection url where perform connection to. Please note that other connection options will override parameters set from url.

For example like that:

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. On heroku you can get the database credentials in the addon settings or of course from the url. So you could write an ormconfig.json for heroku with these credentials.
{
  "name": "default",
  "type": "postgres",
  "url: "postgres://username:password@hostname:5432/databasename"
  "synchronize": false,
  "logging": true,
  "entities": ["src/entity/*.*"]
}

I like option one better, because the url could change on heroku and you wouldn't have to do anything in your code / config-files.

Related