Skip to content

Commit

Permalink
Merge pull request #13 from smartcontractkit/features/merge-env-vars-…
Browse files Browse the repository at this point in the history
…for-db

merge TYPEORM_* env vars onto existing ormconfig.json
  • Loading branch information
rupurt authored Mar 19, 2019
2 parents d35904e + ed2287d commit f9fdf17
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 14 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,3 @@ lib-cov
*.pid
assets/*
build/
ormconfig.production.*
1 change: 0 additions & 1 deletion ormconfig.development.json → ormconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"name": "default",
"type": "postgres",
"host": "localhost",
"port": 5432,
Expand Down
36 changes: 24 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import "reflect-metadata"
import { createConnection, ConnectionOptions, ConnectionOptionsReader } from "typeorm"
import seed from "./seed"
import server from "./server"
import 'reflect-metadata'
import { createConnection } from 'typeorm'
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions'
import seed from './seed'
import server from './server'
import options from '../ormconfig.json'

const nodeEnv = process.env.NODE_ENV || 'development'
const ormconfigPath = `ormconfig.${nodeEnv}.json`
const overridableKeys = ['host', 'port', 'username', 'password', 'database']

const loadOptions = async (configName: string): Promise<ConnectionOptions> => {
const reader = new ConnectionOptionsReader({configName})
return reader.get("default")
// Loads the following ENV vars, giving them precedence.
// i.e. TYPEORM_PORT will replace "port" in ormconfig.json.
const loadOptions = (): PostgresConnectionOptions => {
let envOptions: { [key: string]: string } = {}
for (let v of overridableKeys) {
const envVar = process.env[`TYPEORM_${v.toUpperCase()}`]
if (envVar) {
envOptions[v] = envVar
}
}
return {
...options,
...envOptions
} as PostgresConnectionOptions
}

loadOptions(ormconfigPath).then(options => {
createConnection(options).then(async dbConnection => {
createConnection(loadOptions())
.then(async dbConnection => {
seed(dbConnection)
server(dbConnection)
})
}).catch(error => console.log(error))
.catch(error => console.log(error))
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"noImplicitAny": true,
"baseUrl": ".",
Expand Down

0 comments on commit f9fdf17

Please sign in to comment.