'update'
[qomet.git] / app.js
1 const express = require('express');
2 const app = express();
3 const path = require('path');
4 const cookieParser = require('cookie-parser');
5 const favicon = require('serve-favicon');
6 const logger = require('morgan');
7 const bodyParser = require('body-parser');
8 const params = require(path.join(__dirname, "config", "parameters"));
9
10 app.set('views', path.join(__dirname, 'views'));
11 app.set('view engine', 'pug');
12 app.use(favicon(path.join(__dirname, "public", "favicon", "favicon.ico")));
13 if (app.get('env') === 'development')
14 {
15 // Full logging in development mode
16 app.use(logger('dev'));
17 }
18 else
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 }
26 app.use(bodyParser.json());
27 app.use(bodyParser.urlencoded({ extended: false }));
28 app.use(cookieParser());
29 app.use(express.static(path.join(__dirname, 'public')));
30
31 // Before any request, check cookies
32 app.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
39 let routes = require(path.join(__dirname, "routes", "all"));
40 app.use("/", routes);
41
42 // catch 404 and forward to error handler
43 app.use(function(req, res, next) {
44 let err = new Error('Not Found');
45 err.status = 404;
46 next(err);
47 });
48
49 // Error handler
50 app.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
60 module.exports = app;