Files
2025-08-08 10:47:29 +02:00

115 lines
3.7 KiB
JavaScript

var appEnv = process.env.APP_ENV;
if (appEnv == undefined) {
appEnv = 'development';
}
require('dotenv').config({ path: `.env.${appEnv}` });
const { promisify } = require('util'),
bodyParser = require('body-parser'),
chalk = require('chalk'),
utils = require('./routes/utils'),
exceptionHandler = require('./middlewares/exceptions.handler.js');
var express = require('express'),
session = require('express-session'),
cors = require('cors'),
errorhandler = require('errorhandler'),
mongoose = require('mongoose'),
morgan = require('morgan');
var isProduction = appEnv === 'production';
// Create global app object
var app = express();
app.use(cors());
// Normal express config defaults
//app.use(morgan('combined'));
morgan.token('statusColor', (req, res) => {
let status = (typeof res.headersSent !== 'boolean' ? Boolean(res.header) : res.headersSent)
? res.statusCode
: undefined
return status >= 500 ? chalk.red(status)
: status >= 429 ? chalk.magenta(status)
: status >= 400 ? chalk.yellow(status)
: status >= 300 ? chalk.cyan(status)
: status >= 200 ? chalk.green(status)
: chalk.underline(status);
});
app.use(morgan('[:date[iso]] ":method :url HTTP/:http-version" :statusColor :res[content-length] ":referrer" ":user-agent" :remote-addr'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('method-override')());
app.use(express.static(__dirname + '/public'));
app.use(session({ secret: 'acapisecret', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }));
if (!isProduction) {
app.use(errorhandler());
}
if(isProduction){
mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.set('strictQuery', true);
mongoose.connect(process.env.MONGODB_URI).then(() => {
console.log(`${utils.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully'));
}).catch(() => {
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MongoDB database'));
});
mongoose.set('debug', process.env.DEBUG);
console.log(`${utils.getDateTimeISOString()}`, chalk.red('debug :'), chalk.yellow(process.env.DEBUG));
}
require('./models/mongo');
require('./config/passport');
app.use(require('./routes'));
app.use(exceptionHandler.notFoundErrorHandler);
app.use(exceptionHandler.logErrorHandler);
app.use(exceptionHandler.clientErrorHandler);
app.use(exceptionHandler.fianlErrorHandler);
/*
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`error handler : ${err.message} ${err.err}`));
if (res.headersSent) {
return next(err)
}
res.status(err.status || 500);
if (!isProduction) {
// development error handler will print stacktrace
res.json({errors: {
message: err.message,
error: err.err,
stack: err.stack
}});
} else {
// production error handler no stacktraces leaked to user
res.json({errors: {
message: err.message,
error: {},
stack: {}
}});
}
});
*/
const startServer = async () => {
const port = process.env.SERVER_PORT || 3200;
await promisify(app.listen).bind(app)(port);
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${process.env.APP_ENV} API server listening on port ${port}`));
}
// finally, let's start our server...
startServer();