Skip to content

Commit

Permalink
Use dotenv for configuration management
Browse files Browse the repository at this point in the history
  • Loading branch information
kunalkapadia committed Feb 19, 2017
1 parent 3e520a8 commit 7e42081
Show file tree
Hide file tree
Showing 16 changed files with 71 additions and 46 deletions.
5 changes: 5 additions & 0 deletions .env.example
@@ -0,0 +1,5 @@
NODE_ENV=development
PORT=4040
JWT_SECRET=0a6b944d-d2fb-46fc-a85e-0295c986cd9f
MONGO_HOST=mongodb://localhost/express-mongoose-es6-rest-api-development
MONGO_PORT=27017
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -46,3 +46,6 @@ node_modules

# Optional REPL history
.node_repl_history

# .env
.env
4 changes: 2 additions & 2 deletions .istanbul.yml
@@ -1,6 +1,6 @@
verbose: false
instrumentation:
excludes: ['dist/**', 'coverage/**', 'gulpfile.babel.js', 'config/env/development.js', 'config/env/production.js']
excludes: ['dist/**', 'coverage/**', 'gulpfile.babel.js']
include-all-sources: true
reporting:
print: summary
Expand All @@ -22,4 +22,4 @@ check:
statements: 50
lines: 50
branches: 30
functions: 20
functions: 20
44 changes: 44 additions & 0 deletions config/config.js
@@ -0,0 +1,44 @@
import Joi from 'joi';

// require and configure dotenv, will load vars in .env in PROCESS.ENV
require('dotenv').config();

// define validation for all the env vars
const envVarsSchema = Joi.object({
NODE_ENV: Joi.string()
.allow(['development', 'production', 'test', 'provision'])
.default('development'),
PORT: Joi.number()
.default(4040),
MONGOOSE_DEBUG: Joi.boolean()
.when('NODE_ENV', {
is: Joi.string().equal('development'),
then: Joi.boolean().default(true),
otherwise: Joi.boolean().default(false)
}),
JWT_SECRET: Joi.string().required()
.description('JWT Secret required to sign'),
MONGO_HOST: Joi.string().required()
.description('Mongo DB host url'),
MONGO_PORT: Joi.number()
.default(27017)
}).unknown()
.required();

const { error, value: envVars } = Joi.validate(process.env, envVarsSchema);
if (error) {
throw new Error(`Config validation error: ${error.message}`);
}

const config = {
env: envVars.NODE_ENV,
port: envVars.PORT,
mongooseDebug: envVars.MONGOOSE_DEBUG,
jwtSecret: envVars.JWT_SECRET,
mongo: {
host: envVars.MONGO_HOST,
port: envVars.MONGO_PORT
}
};

export default config;
9 changes: 0 additions & 9 deletions config/env/development.js

This file was deleted.

10 changes: 0 additions & 10 deletions config/env/index.js

This file was deleted.

8 changes: 0 additions & 8 deletions config/env/production.js

This file was deleted.

8 changes: 0 additions & 8 deletions config/env/test.js

This file was deleted.

2 changes: 1 addition & 1 deletion config/express.js
Expand Up @@ -11,7 +11,7 @@ import expressValidation from 'express-validation';
import helmet from 'helmet';
import winstonInstance from './winston';
import routes from '../server/routes/index.route';
import config from './env';
import config from './config';
import APIError from '../server/helpers/APIError';

const app = express();
Expand Down
4 changes: 2 additions & 2 deletions gulpfile.babel.js
Expand Up @@ -8,13 +8,13 @@ const plugins = gulpLoadPlugins();

const paths = {
js: ['./**/*.js', '!dist/**', '!node_modules/**', '!coverage/**'],
nonJs: ['./package.json', './.gitignore'],
nonJs: ['./package.json', './.gitignore', './.env'],
tests: './server/tests/*.js'
};

// Clean up dist and coverage directory
gulp.task('clean', () =>
del.sync(['dist/**', 'coverage/**', '!dist', '!coverage'])
del.sync(['dist/**', 'dist/.*', 'coverage/**', '!dist', '!coverage'])
);

// Copy non-js files to dist
Expand Down
7 changes: 5 additions & 2 deletions index.js
@@ -1,6 +1,8 @@
import mongoose from 'mongoose';
import util from 'util';
import config from './config/env';

// config should be imported before importing any other file
import config from './config/config';
import app from './config/express';

const debug = require('debug')('express-mongoose-es6-rest-api:index');
Expand All @@ -12,7 +14,8 @@ Promise = require('bluebird'); // eslint-disable-line no-global-assign
mongoose.Promise = Promise;

// connect to mongo db
mongoose.connect(config.db, { server: { socketOptions: { keepAlive: 1 } } });
const mongoUri = `${config.mongo.host}:${config.mongo.port}`;
mongoose.connect(mongoUri, { server: { socketOptions: { keepAlive: 1 } } });
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${config.db}`);
});
Expand Down
3 changes: 2 additions & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "express-mongoose-es6-rest-api",
"version": "1.0.0",
"version": "2.0.0",
"description": "A Boilerplate application for building REST APIs using express, mongoose in ES6 with code coverage",
"author": "Kunal Kapadia <kunalkapadia12@gmail.com>",
"main": "index.js",
Expand Down Expand Up @@ -47,6 +47,7 @@
"cookie-parser": "1.4.3",
"cors": "2.8.1",
"debug": "^2.4.5",
"dotenv": "^4.0.0",
"express": "4.14.0",
"express-jwt": "5.1.0",
"express-validation": "1.0.1",
Expand Down
2 changes: 1 addition & 1 deletion server/controllers/auth.controller.js
@@ -1,7 +1,7 @@
import jwt from 'jsonwebtoken';
import httpStatus from 'http-status';
import APIError from '../helpers/APIError';
import config from '../../config/env';
import config from '../../config/config';

// sample user, used for authentication
const user = {
Expand Down
2 changes: 1 addition & 1 deletion server/routes/auth.route.js
Expand Up @@ -3,7 +3,7 @@ import validate from 'express-validation';
import expressJwt from 'express-jwt';
import paramValidation from '../../config/param-validation';
import authCtrl from '../controllers/auth.controller';
import config from '../../config/env';
import config from '../../config/config';

const router = express.Router(); // eslint-disable-line new-cap

Expand Down
2 changes: 1 addition & 1 deletion server/tests/auth.test.js
Expand Up @@ -3,7 +3,7 @@ import httpStatus from 'http-status';
import jwt from 'jsonwebtoken';
import chai, { expect } from 'chai';
import app from '../../index';
import config from '../../config/env';
import config from '../../config/config';

chai.config.includeStack = true;

Expand Down
4 changes: 4 additions & 0 deletions yarn.lock
Expand Up @@ -1397,6 +1397,10 @@ dont-sniff-mimetype@1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/dont-sniff-mimetype/-/dont-sniff-mimetype-1.0.0.tgz#5932890dc9f4e2f19e5eb02a20026e5e5efc8f58"

dotenv@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-4.0.0.tgz#864ef1379aced55ce6f95debecdce179f7a0cd1d"

duplexer2@0.0.2:
version "0.0.2"
resolved "https://registry.yarnpkg.com/duplexer2/-/duplexer2-0.0.2.tgz#c614dcf67e2fb14995a91711e5a617e8a60a31db"
Expand Down

0 comments on commit 7e42081

Please sign in to comment.