const express = require('express'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const methodOverride = require('method-override'); const cors = require('cors'); const compression = require('compression'); const log = require('./log')(module); const config = require('./config'); const cache = require('apicache').options({ debug: config.get('debug') }).middleware; const app = express(); const api = require('./routes/api'); const mongoose = require('./db/mongoose'); const db = mongoose(); const passport = require('passport'); const jwt = require('jwt-simple'); app.use(passport.initialize()); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(cors()); app.use(methodOverride()); app.use(cache('1 day')); app.use(compression(9)); app.use(api); // catch 404 and forward to error handler app.use((req, res, next) => { res.status(404); log.debug('%s %d %s', req.method, res.statusCode, req.url); res.json({ error: 'Not found' }).end(); }); // error handlers app.use((err, req, res, next) => { res.status(err.status || 500); log.error('%s %d %s', req.method, res.statusCode, err.message); res.json({ error: err.message }).end(); }); module.exports = app;