Last active
October 8, 2021 07:20
-
-
Save ignavan39/bfd5bc4d456791e9c51afeefb863bb1a to your computer and use it in GitHub Desktop.
config.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dotenv from 'dotenv'; | |
import { DeepPartial } from 'typeorm'; | |
type Join<K, P> = K extends string | number | |
? P extends string | number | |
? `${K}${'' extends P ? '' : '.'}${P}` | |
: never | |
: never; | |
type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]]; | |
export type Paths<T, D extends number = 10> = [D] extends [never] | |
? never | |
: T extends object | |
? { | |
[K in keyof T]-?: K extends string | number ? `${K}` | Join<K, Paths<T[K], Prev[D]>> : never; | |
}[keyof T] | |
: ''; | |
dotenv.config(); | |
export class Configuration { | |
jwtSecret: string; | |
database: { | |
password: string; | |
username: string; | |
name: string; | |
host: string; | |
}; | |
port?: number; | |
} | |
class ConfigService { | |
private config: Configuration; | |
constructor() { | |
this.config = { | |
jwtSecret: process.env.JWT_SECRET, | |
database: { | |
username: process.env.DATABASE_USER, | |
name: process.env.DATABASE_NAME, | |
password: process.env.DATABASE_PASSWORD, | |
host: process.env.DATABASE_HOST || 'localhost', | |
}, | |
port: Number.parseInt(process.env.PORT) || 5000, | |
}; | |
} | |
getValue(key: Paths<Configuration>) { | |
const keys = key.split('.'); | |
if (keys.length > 1) { | |
let nestedObj = this.config; | |
for (let nestedKey of keys) { | |
nestedObj = nestedObj[nestedKey]; | |
} | |
return nestedObj; | |
} | |
return this.config[key]; | |
} | |
} | |
export const configService = new ConfigService(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { configService } from 'src/config'; | |
import { Connection, createConnection } from 'typeorm'; | |
export const getDatabaseConnection = async (): Promise<Connection> => | |
createConnection({ | |
type: 'postgres', | |
synchronize: true, | |
port: 5432, | |
host: configService.getValue('database.host'), | |
username: configService.getValue('database.username'), | |
password: configService.getValue('database.password'), | |
database: configService.getValue('database.name'), | |
entities: ['src/entities/*.entity{.ts,.js}'], | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment