Skip to content

Commit

Permalink
Add validation on the env variables config
Browse files Browse the repository at this point in the history
  • Loading branch information
hagopj13 committed Nov 10, 2019
1 parent d678ff2 commit e559c13
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 10 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
PORT=3000
MONGODB_URL=mongodb://127.0.0.1:27017/node-boilerplate
MONGODB_URL=mongodb://localhost:27017/node-boilerplate
JWT_SECRET=thisisasamplesecret
JWT_ACCESS_EXPIRATION_MINUTES=30
JWT_REFRESH_EXPIRATION_DAYS=30
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ branches:
env:
global:
- PORT=3000
- MONGODB_URL=mongodb://localhost:27017/node-boilerplate
- JWT_SECRET=thisisasamplesecret
- JWT_ACCESS_EXPIRATION_MINUTES=30
- JWT_REFRESH_EXPIRATION_DAYS=30
Expand Down
44 changes: 35 additions & 9 deletions src/config/config.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,46 @@
const dotenv = require('dotenv');
const path = require('path');
const Joi = require('@hapi/joi');

dotenv.config({
path: path.join(__dirname, '../../.env'),
});
dotenv.config({ path: path.join(__dirname, '../../.env') });

const envVarsSchema = Joi.object()
.keys({
NODE_ENV: Joi.string()
.valid('production', 'development', 'test')
.required(),
PORT: Joi.number().default(3000),
MONGODB_URL: Joi.string()
.required()
.description('Mongo DB url'),
JWT_SECRET: Joi.string()
.required()
.description('JWT secret key'),
JWT_ACCESS_EXPIRATION_MINUTES: Joi.number()
.default(30)
.description('minutes after which access tokens expire'),
JWT_REFRESH_EXPIRATION_DAYS: Joi.number()
.default(30)
.description('days after which refresh tokens expire'),
})
.unknown();

const { value: envVars, error } = envVarsSchema.prefs({ errors: { label: 'key' } }).validate(process.env);

if (error) {
throw new Error(`Config validation error: ${error.message}`);
}

module.exports = {
env: process.env.NODE_ENV,
port: process.env.PORT,
env: envVars.NODE_ENV,
port: envVars.PORT,
mongoose: {
url: process.env.MONGODB_URL,
url: envVars.MONGODB_URL,
options: { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true },
},
jwt: {
secret: process.env.JWT_SECRET,
accessExpirationMinutes: parseInt(process.env.JWT_ACCESS_EXPIRATION_MINUTES, 10),
refreshExpirationDays: parseInt(process.env.JWT_REFRESH_EXPIRATION_DAYS, 10),
secret: envVars.JWT_SECRET,
accessExpirationMinutes: envVars.JWT_ACCESS_EXPIRATION_MINUTES,
refreshExpirationDays: envVars.JWT_REFRESH_EXPIRATION_DAYS,
},
};

0 comments on commit e559c13

Please sign in to comment.