Attempt to resurrect qomet code - need some rewrite
[qomet.git] / app.js
... / ...
CommitLineData
1const express = require('express');
2const app = express();
3const path = require('path');
4const cookieParser = require('cookie-parser');
5const favicon = require('serve-favicon');
6const logger = require('morgan');
7const bodyParser = require('body-parser');
8const params = require(path.join(__dirname, "config", "parameters"));
9
10app.set('views', path.join(__dirname, 'views'));
11app.set('view engine', 'pug');
12app.use(favicon(path.join(__dirname, "public", "favicon", "favicon.ico")));
13if (app.get('env') === 'development')
14{
15 // Full logging in development mode
16 app.use(logger('dev'));
17}
18else
19{
20 app.set('trust proxy', true); //http://dev.rdybarra.com/2016/06/23/Production-Logging-With-Morgan-In-Express/
21 // In prod, only log error responses (https://github.com/expressjs/morgan)
22 app.use(logger('combined', {
23 skip: function (req, res) { return res.statusCode < 400 }
24 }));
25}
26app.use(bodyParser.json());
27app.use(bodyParser.urlencoded({ extended: false }));
28app.use(cookieParser());
29app.use(express.static(path.join(__dirname, 'public')));
30
31// Before any request, check cookies
32app.use(function(req, res, next) {
33 res.locals.loggedIn = !!req.cookies.token;
34 res.locals.myInitials = req.cookies.initials; //may be undefined
35 next();
36});
37
38// Routing
39let routes = require(path.join(__dirname, "routes", "all"));
40app.use("/", routes);
41
42// catch 404 and forward to error handler
43app.use(function(req, res, next) {
44 let err = new Error('Not Found');
45 err.status = 404;
46 next(err);
47});
48
49// Error handler
50app.use(function(err, req, res, next) {
51 // Set locals, only providing error in development (TODO: difference req.app and app ?!)
52 res.locals.message = err.message;
53 if (app.get('env') === 'development')
54 console.log(err);
55 res.locals.error = req.app.get('env') === 'development' ? err : {};
56 res.status(err.status || 500);
57 res.render('error');
58});
59
60module.exports = app;