Skip to content

Commit

Permalink
Config validation
Browse files Browse the repository at this point in the history
  • Loading branch information
likui628 committed Sep 24, 2024
1 parent 9431669 commit d583874
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
23 changes: 23 additions & 0 deletions src/config/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { z } from 'zod'

const envVarsSchema = z.object({
PORT: z.string().default('5000'),
JWT_SECRET: z.string(),
DATABASE_URL: z.string(),
})

let envVars: z.infer<typeof envVarsSchema>
try {
envVars = envVarsSchema.parse(process.env)
} catch (error) {
if (error instanceof z.ZodError) {
const formattedErrors = error.errors
.map((err) => `${err.path.join('.')} - ${err.message}`)
.join('\n')

console.error('Environment variable validation errors:\n', formattedErrors)
}
process.exit(1)
}

export default envVars
3 changes: 2 additions & 1 deletion src/config/passport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import {
StrategyOptions,
} from 'passport-jwt'
import { prisma } from '../utils'
import config from './config'

const options: StrategyOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET || 'your_jwt_secret',
secretOrKey: config.JWT_SECRET,
}

export const jwtStrategy = new JwtStrategy(
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import app from './app'
import config from './config/config'

const port = process.env.PORT || 5000
const port = config.PORT || 5000
app.listen(port, () => {
/* eslint-disable no-console */
console.log(`Listening: http://localhost:${port}`)
Expand Down

0 comments on commit d583874

Please sign in to comment.