Skip to content

Commit

Permalink
[#12] feat: add env validation
Browse files Browse the repository at this point in the history
  • Loading branch information
glemenneo committed Sep 21, 2024
1 parent 2df67bb commit 171394d
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 10 deletions.
13 changes: 13 additions & 0 deletions backend/user-service/src/common/config.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ValidationError } from 'class-validator'
import { Config } from '../types/Config'
import logger from './logger.util'

const config: Config = Config.fromEnv(process.env)
config.validateOrReject().catch((errors: ValidationError[]) => {
logger.error(
`[Config] Invalid or missing configuration: ${errors.map((error: ValidationError) => error.property).join(', ')}`
)
process.exit(1)
})

export default config
14 changes: 4 additions & 10 deletions backend/user-service/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
import 'dotenv/config'
import http, { Server } from 'http'
import config from './common/config.util'
import logger from './common/logger.util'
import connectToDatabase from './common/mongodb.util'
import index from './index'

const port: string = process.env.PORT ?? '3000'
const server: Server = http.createServer(index)
server.listen(port, async () => {
logger.info(`[Init] Server is listening on port ${port}`)
server.listen(config.PORT, async () => {
logger.info(`[Init] Server is listening on port ${config.PORT}`)
})

const connectionString: string | undefined = process.env.DB_URL
if (!connectionString) {
logger.error(`[Init] DB_URL is not set`)
process.exit(1)
}

connectToDatabase(connectionString)
connectToDatabase(config.DB_URL)
48 changes: 48 additions & 0 deletions backend/user-service/src/types/Config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { IsBase64, IsEnum, IsNotEmpty, IsNumberString, IsString, validateOrReject } from 'class-validator'

export class Config {
@IsEnum(['development', 'production', 'test'])
NODE_ENV: string

@IsNumberString()
@IsNotEmpty()
PORT: string

@IsString()
@IsNotEmpty()
DB_URL: string

@IsBase64()
ACCESS_TOKEN_PRIVATE_KEY: string

@IsBase64()
ACCESS_TOKEN_PUBLIC_KEY: string

constructor(
NODE_ENV: string,
PORT: string,
DB_URL: string,
ACCESS_TOKEN_PRIVATE_KEY: string,
ACCESS_TOKEN_PUBLIC_KEY: string
) {
this.NODE_ENV = NODE_ENV ?? 'development'
this.PORT = PORT ?? '3002'
this.DB_URL = DB_URL
this.ACCESS_TOKEN_PRIVATE_KEY = ACCESS_TOKEN_PRIVATE_KEY
this.ACCESS_TOKEN_PUBLIC_KEY = ACCESS_TOKEN_PUBLIC_KEY
}

static fromEnv(env: { [key: string]: string | undefined }): Config {
return new Config(
env.NODE_ENV!,
env.PORT!,
env.DB_URL!,
env.ACCESS_TOKEN_PRIVATE_KEY!,
env.ACCESS_TOKEN_PUBLIC_KEY!
)
}

async validateOrReject(): Promise<void> {
await validateOrReject(this)
}
}

0 comments on commit 171394d

Please sign in to comment.