Skip to content

Commit

Permalink
feat: add project dotenv friendly
Browse files Browse the repository at this point in the history
you can now use environment variables
  • Loading branch information
Silent-Watcher committed Oct 18, 2023
1 parent 027f3c8 commit 555dc7e
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 3 deletions.
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# values : drv| prod
APP_ENV =

# local : 3000
PORT =

# local : mongodb://127.0.0.1:27017
DB_URL =
DB_NAME =
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
todo.txt
node_modules
.env
.env.dev
40 changes: 40 additions & 0 deletions config/dotenv.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const dotenv = require('dotenv');
const path = require('path');
const { env } = require('node:process');

/**
* ! define mandatory environment variables inside the envVars array
*/
const envVars = ['PORT'];

dotenv.config();
const ENV_BASE_PATH = path.join(__dirname, '..', `.env.${env.APP_ENV}`);
dotenv.config({
path: ENV_BASE_PATH,
});

function isEnvVarExits(envVars) {
return new Promise((res, rej) => {
let notDefinedEnvVars = envVars.filter((envVar) => !env[envVar]);
if (notDefinedEnvVars.length > 0)
throw {
code: 500,
error: {
message: `following env vars are not defined:\n ${notDefinedEnvVars.join(
', ',
)}`,
},
};
return res();
});
}

async function runEnv(envVars) {
try {
let result = await isEnvVarExits(envVars);
} catch (error) {
process.exit(1);
}
}

runEnv(envVars);
4 changes: 2 additions & 2 deletions config/mongoose.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict';
const { default: mongoose } = require('mongoose');
const { env } = require('process');

const DB_NAME = 'jwt';
const DB_URL = `mongodb://127.0.0.1:27017/${DB_NAME}`;
const DB_URL = `${env.DB_URL}/${env.DB_NAME}`;

const connectToDb = async (dbUrl) => await mongoose.connect(dbUrl);

Expand Down
4 changes: 3 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ const http = require('http');
const errorHandler = require('./middlewares/global/errorHandlerMiddleware');
const notFoundErrorHandler = require('./middlewares/global/notFoundErrorHandler.middleware');
const router = require('./routes/router');
const { env } = require('process');

require('./config/dotenv.config');
require('./config/mongoose.config');

const app = express();
const server = http.createServer({}, app);
const PORT = 3000;
const PORT = env.PORT;

app.use(express.json(), express.urlencoded({ extended: true }));

Expand Down

0 comments on commit 555dc7e

Please sign in to comment.