Skip to content

Commit d583874

Browse files
committed
Config validation
1 parent 9431669 commit d583874

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

src/config/config.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { z } from 'zod'
2+
3+
const envVarsSchema = z.object({
4+
PORT: z.string().default('5000'),
5+
JWT_SECRET: z.string(),
6+
DATABASE_URL: z.string(),
7+
})
8+
9+
let envVars: z.infer<typeof envVarsSchema>
10+
try {
11+
envVars = envVarsSchema.parse(process.env)
12+
} catch (error) {
13+
if (error instanceof z.ZodError) {
14+
const formattedErrors = error.errors
15+
.map((err) => `${err.path.join('.')} - ${err.message}`)
16+
.join('\n')
17+
18+
console.error('Environment variable validation errors:\n', formattedErrors)
19+
}
20+
process.exit(1)
21+
}
22+
23+
export default envVars

src/config/passport.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@ import {
44
StrategyOptions,
55
} from 'passport-jwt'
66
import { prisma } from '../utils'
7+
import config from './config'
78

89
const options: StrategyOptions = {
910
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
10-
secretOrKey: process.env.JWT_SECRET || 'your_jwt_secret',
11+
secretOrKey: config.JWT_SECRET,
1112
}
1213

1314
export const jwtStrategy = new JwtStrategy(

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import app from './app'
2+
import config from './config/config'
23

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

0 commit comments

Comments
 (0)