|
| 1 | +import Joi from 'joi'; |
| 2 | + |
| 3 | +// require and configure dotenv, will load vars in .env in PROCESS.ENV |
| 4 | +require('dotenv').config(); |
| 5 | + |
| 6 | +// define validation for all the env vars |
| 7 | +const envVarsSchema = Joi.object({ |
| 8 | + NODE_ENV: Joi.string() |
| 9 | + .allow(['development', 'production', 'test', 'provision']) |
| 10 | + .default('development'), |
| 11 | + PORT: Joi.number() |
| 12 | + .default(4040), |
| 13 | + MONGOOSE_DEBUG: Joi.boolean() |
| 14 | + .when('NODE_ENV', { |
| 15 | + is: Joi.string().equal('development'), |
| 16 | + then: Joi.boolean().default(true), |
| 17 | + otherwise: Joi.boolean().default(false) |
| 18 | + }), |
| 19 | + JWT_SECRET: Joi.string().required() |
| 20 | + .description('JWT Secret required to sign'), |
| 21 | + MONGO_HOST: Joi.string().required() |
| 22 | + .description('Mongo DB host url'), |
| 23 | + MONGO_PORT: Joi.number() |
| 24 | + .default(27017) |
| 25 | +}).unknown() |
| 26 | + .required(); |
| 27 | + |
| 28 | +const { error, value: envVars } = Joi.validate(process.env, envVarsSchema); |
| 29 | +if (error) { |
| 30 | + throw new Error(`Config validation error: ${error.message}`); |
| 31 | +} |
| 32 | + |
| 33 | +const config = { |
| 34 | + env: envVars.NODE_ENV, |
| 35 | + port: envVars.PORT, |
| 36 | + mongooseDebug: envVars.MONGOOSE_DEBUG, |
| 37 | + jwtSecret: envVars.JWT_SECRET, |
| 38 | + mongo: { |
| 39 | + host: envVars.MONGO_HOST, |
| 40 | + port: envVars.MONGO_PORT |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +export default config; |
0 commit comments