Skip to content

Commit

Permalink
Install pg-connection-string to parse db options from env variable (a…
Browse files Browse the repository at this point in the history
…dpating to Heroku)
  • Loading branch information
javieraviles committed Jun 1, 2018
1 parent 664c7a2 commit 1a2f165
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 14 deletions.
4 changes: 3 additions & 1 deletion .example.env
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
NODE_PORT=3000
NODE_ENV=development
JWT_SECRET=your-secret-whatever
JWT_SECRET=your-secret-whatever
DATABASE_URL=postgres://user:pass@localhost:5432/apidb
TYPEORM_DRIVER_TYPE=postgres
13 changes: 9 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"koa-jwt": "^3.3.2",
"koa-router": "^7.4.0",
"pg": "^7.4.3",
"pg-connection-string": "^2.0.0",
"reflect-metadata": "^0.1.12",
"typeorm": "^0.2.6",
"winston": "^2.4.2"
Expand Down
22 changes: 13 additions & 9 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,29 @@ import * as winston from 'winston';
import * as dotenv from 'dotenv';
import { createConnection } from 'typeorm';
import 'reflect-metadata';
import * as PostgressConnectionStringParser from 'pg-connection-string';

import { User } from './entity/user';
import { logger } from './logging';
import { config } from './config';
import { router } from './routes';

// Load environment variables from .env file, where API keys and passwords are configured
dotenv.config({ path: '.env' });

// Get DB connection options from env variable
const connectionOptions = PostgressConnectionStringParser.parse(process.env.DATABASE_URL);

// create connection with database
// note that its not active database connection
// TypeORM creates you connection pull to uses connections from pull on your requests
createConnection({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'user',
password: 'pass',
database: 'apidb',
type: process.env.TYPEORM_DRIVER_TYPE,
host: connectionOptions.host,
port: connectionOptions.port,
username: connectionOptions.user,
password: connectionOptions.password,
database: connectionOptions.database,
synchronize: true,
logging: false,
entities: [
Expand All @@ -31,9 +38,6 @@ createConnection({

const app = new Koa();

// Load environment variables from .env file, where API keys and passwords are configured
dotenv.config({ path: '.env' });

// Provides important security headers to make your app more secure
app.use(helmet());

Expand Down

0 comments on commit 1a2f165

Please sign in to comment.