adejs/index.js

114 lines
2.8 KiB
JavaScript

const config = require('./settings/config.js');
require('app-module-path').addPath(config.BASE_DIR);
require('app-module-path').addPath(config.UTILS_DIR);
require('app-module-path').addPath(config.CONTROLLERS_DIR);
const express = require('express');
const pug = require('pug');
const http = require('http');
const path = require('path');
const log = require('log');
const model = require('model');
const repl = require('repl');
const User = require('auth/models');
// Load models
model.load(config.CONTROLLERS_DIR);
function startServer() {
let app = express();
let http = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
let session = require('cookie-session');
let cookieParser = require('cookie-parser');
app.set('view engine', 'pug');
app.set('trust proxy', 1);
app.use(cookieParser(config.SECRET_KEY));
app.use(session({keys:[config.SECRET_KEY]}));
// Log request and time to answer
app.use(function(req, res, next) {
let start = Date.now();
res.on('finish', function() {
log.request(req, res, Date.now() - start);
});
res.locals.session = req.session;
if (req.session.user !== undefined) {
req.session.user = User.fromJSON(req.session.user);
}
next();
});
// Give app access to all urls
app.use(require('create-url'));
// Load controllers
require('controllers')(app, config.CONTROLLERS_DIR);
// Static files
app.use('/static', express.static(config.STATIC_DIR));
// When route not found, raise not found
app.use(function(req, res) {
res.status(404);
res.setHeader('Content-Type', 'text/html');
res.render(config.BASE_DIR + '/templates/404.pug', res.locals, function(err, result) {
if (err)
console.log(err);
res.send(result);
});
});
http.listen(config.PORT, config.LISTEN_ADDRESS, function() {
log.ready(
'Now listening ' + config.LISTEN_ADDRESS +
':' + config.PORT
);
});
// On sigint, stop the server
process.on('SIGINT', function() {
process.stdout.write('\r');
log.debug('Stopping server...');
process.exit(0);
});
}
const commands = {
runserver: startServer,
reinitdb: model.reinitialize,
shell: repl.start,
}
function showHelp() {
console.log("Commands available:");
for (let command in commands) {
console.log('\t' + command);
}
}
if (require.main === module) {
if (process.argv.length != 3) {
showHelp();
return;
}
let command = process.argv[2];
if (commands[command] === undefined) {
showHelp();
return;
}
commands[command]();
}