Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I specify the DATABASE_URL in ormconfig.json?

I am trying to deploy my Vesper server to Heroku and Vesper requires an ormconfig.json file.

This works just fine when I use my local db because I can fill out all the fields that will combine into the connection string. However, when I add a db in Heroku I just get the full url and I can't find where to put it.

This is my ormconfig.json right now.

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "password": "password",
  "database": "test",
  "synchronize": true,
  "entities": ["target/entity/**/*.js"],
  "migrations": ["target/migrations/*.js"],
  "cli": {
    "migrationsDir": "src/migrations"
  }
}

I'm hoping I could replace most fields with just the database_url but I can't find any documentation stating under what name I should put it.

like image 331
Stefan Wullems Avatar asked Mar 04 '23 19:03

Stefan Wullems


1 Answers

You can use an url parser for heroku env var parsing such as pg-connection-string https://www.npmjs.com/package/pg-connection-string

Then you use the createConnection function given by TypeOrm to initialize TypeOrm on the server side.

import * as PostgressConnectionStringParser from "pg-connection-string";

const databaseUrl: string = process.env.DATABASE_URL;
const connectionOptions = PostgressConnectionStringParser.parse(databaseUrl);
const typeOrmOptions: PostgresConnectionOptions = {
    type: "postgres",
    name: connectionOptions.name,
    host: connectionOptions.host,
    port: connectionOptions.port,
    username: connectionOptions.username,
    password: connectionOptions.password,
    database: connectionOptions.database,
    synchronize: true,
    entities: ["target/entity/**/*.js"],
    extra: {
        ssl: true
    }
};
const connection = createConnection(typeOrmOptions);
...

If you manage different configurations, you will probably have to modify this snippet so you can enable / disable ssl depending on the environment for instance (no ssl in dev mode, ts-node fetches entities in .ts format, etc...).

If you really need to generate ormconfig.json, then I'm afraid you have to generate the file from a script file, with the former code, just add a write part:

...
const json = JSON.stringify(typeOrmOptions, null, 2);
fs.writeFile("./target/ormconfig.json", json, (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log("File has been created");
});
like image 152
zenbeni Avatar answered May 08 '23 09:05

zenbeni