Search code examples
node.jspostgresqlherokunestjsheroku-postgres

How do I connect to Heroku Postgres from Nest.js?


When running heroku config I see (with some omissions)

DATABASE_URL: postgres://<xxxx>:<xxxx>@ec2-xx-xx-xxx-xx.compute-1.amazonaws.com:5432/dm74hmu71b97n

which I know is of form postgres://<user>:<password>@<hostname>:<port>/<database>. But right now in my Nest.JS app I connect to postgres like this:

@Module({
    imports: [
        TypeOrmModule.forRootAsync({
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory: (configService: ConfigService) => ({
                type: 'postgres',
                host: configService.get('POSTGRES_HOST'),
                port: configService.get('POSTGRES_PORT'),
                username: configService.get('POSTGRES_USER'),
                password: configService.get('POSTGRES_PASSWORD'),
                database: configService.get('POSTGRES_DB'),
                entities: [__dirname + '/../**/*.entity{.ts,.js}'],
                synchronize: false,
            }),
        }),
    ],
})
export class DatabaseModule {}

I suppose I could manually parse process.env.DATABASE_URL I figured there must be a better/easier way.


Solution

  • useFactory: (configService: ConfigService) => ({
        url: configService.get('DATABASE_URL'),
        type: 'postgres',
        entities: [__dirname + '/../**/*.entity{.ts,.js}'],
        synchronize: false,
    }),