env variables through different file and optimizing error handling with middleware

This commit is contained in:
Arjun Patel
2019-01-13 22:38:44 -08:00
parent 43bf237942
commit 23f40dc73b
13 changed files with 111 additions and 119 deletions
+14 -7
View File
@@ -1,9 +1,8 @@
//require dependencies
const express = require('express'),
app = express(),
router = express.Router(),
bodyParser = require('body-parser'),
port = process.env.PORT || 4200,
port = process.env.PORT,
db = require('./app/config/db.config.js');
app.use(bodyParser.json());
@@ -34,13 +33,13 @@ db.sequelize
console.error('Unable to connect to the database:', err);
});
// force: true will drop the table if it already exists
//force: true will drop the table if it already exists
const drop_tables = false;
db.sequelize.sync({ force: drop_tables }).then(() => {
console.log(`Drop and Resync with { force: ${drop_tables} }`);
});
//define a route, usually this would be a bunch of routes imported from another file
//main route for api; perhaps for api docs frontend
app.get('/', function(req, res, next) {
res.send('Welcome to the Ucharify API');
});
@@ -49,18 +48,26 @@ app.get('/', function(req, res, next) {
app.use('/api/donors', require('./app/routes/donors.route.js'));
app.use('/api/auth', require('./app/routes/auth.route.js'));
//404 not found error handling on any other routes
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
});
//General error handler for anything
app.use((error, req, res, next) => {
//can log the error internally
// console.log(error);
if (req.app.get('env') !== 'development' && req.app.get('env') !== 'test') {
delete error.stack;
}
//status is set from other logic depending on the error itself
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
error: error.message
});
});