92 lines
3.3 KiB
JavaScript
92 lines
3.3 KiB
JavaScript
var appEnv = process.env.APP_ENV;
|
|
if (appEnv == undefined) {
|
|
appEnv = 'development';
|
|
}
|
|
require('dotenv').config({ path: `config/env/.env.${appEnv}` });
|
|
const { promisify } = require('util'),
|
|
chalk = require('chalk');
|
|
//bodyParser = require('body-parser')
|
|
var express = require('express'),
|
|
session = require('express-session'),
|
|
cors = require('cors'),
|
|
errorhandler = require('errorhandler'),
|
|
morgan = require('morgan');
|
|
|
|
const DateUtilities = require('./src/utils/dateUtilities'),
|
|
exceptionHandler = require('./src/middlewares/exceptions.handler'),
|
|
connectDb = require('./src/database/connectDb'),
|
|
config = require('./src/config');
|
|
|
|
// Create global app object
|
|
var app = express();
|
|
app.use(cors());
|
|
|
|
// Morgan status code color config
|
|
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);
|
|
});
|
|
// Morgan log line config
|
|
app.use(morgan('[:date[iso]] ":method :url HTTP/:http-version" :statusColor :res[content-length] ":referrer" ":user-agent" :remote-addr'));
|
|
|
|
//use express.json() to parse incoming requests with JSON payloads
|
|
app.use(express.json());
|
|
//parse incoming requests with urlencoded payloads
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
//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: config.secret, cookie: { maxAge: config.session_lifetime }, resave: false, saveUninitialized: false }));
|
|
|
|
if (appEnv !== 'production') {
|
|
app.use(errorhandler());
|
|
}
|
|
|
|
require('./src/database/models/mongo');
|
|
config.initAuth();
|
|
//config.initApiKey();
|
|
|
|
// Register routes AFTER connections are established
|
|
const setupRoutes = () => {
|
|
app.use(require('./src/routes'));
|
|
|
|
// Exception handlers MUST be AFTER routes
|
|
app.use(exceptionHandler.notFoundErrorHandler);
|
|
app.use(exceptionHandler.logErrorHandler);
|
|
//app.use(exceptionHandler.clientErrorHandler);
|
|
app.use(exceptionHandler.fianlErrorHandler);
|
|
};
|
|
|
|
const startServer = async () => {
|
|
try {
|
|
// Initialize database connections and create relationships FIRST
|
|
await connectDb.connectAllDb();
|
|
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('All database connections established, relationships loaded'));
|
|
|
|
// NOW register the routes after connections are ready
|
|
setupRoutes();
|
|
|
|
// Start the HTTP server
|
|
const port = process.env.SERVER_PORT || 3200;
|
|
await promisify(app.listen).bind(app)(port);
|
|
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green(`${process.env.APP_ENV} API server listening on port ${port}`));
|
|
} catch (error) {
|
|
console.error(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Failed to start server:'), error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
// finally, let's start our server...
|
|
startServer();
|