2019-10-21 16:56:21 +00:00
|
|
|
// vim: set ts=2 sw=2 et tw=80:
|
|
|
|
|
|
|
|
const express = require('express');
|
|
|
|
const path = require('path');
|
|
|
|
const logger = require('morgan');
|
|
|
|
const bodyParser = require('body-parser');
|
|
|
|
const kleiDust = require('klei-dust');
|
|
|
|
const methodOverride = require('method-override');
|
|
|
|
const fs = require('fs');
|
|
|
|
|
|
|
|
const app = express();
|
|
|
|
|
|
|
|
//configure app
|
|
|
|
app.use(logger('dev'));
|
|
|
|
app.set('views', __dirname + '/views');
|
|
|
|
app.engine('dust', kleiDust.dust);
|
|
|
|
app.set('view engine', 'dust');
|
|
|
|
app.set('view options', { layout: false });
|
|
|
|
|
|
|
|
app.use(methodOverride('_method'));
|
|
|
|
|
|
|
|
// parse application/x-www-form-urlencoded
|
|
|
|
app.use(bodyParser.urlencoded({ extended: false }));
|
|
|
|
|
|
|
|
// parse application/json
|
|
|
|
app.use(bodyParser.json());
|
|
|
|
|
|
|
|
app.use(express.static('public'));
|
|
|
|
|
|
|
|
fs.readFile(__dirname + '/db.json', { encoding: 'utf8' }, (e, data) => {
|
|
|
|
if (e) {
|
|
|
|
if (e.code === 'ENOENT') {
|
|
|
|
console.info("No database file. Initializing with empty data");
|
|
|
|
} else console.error(e);
|
|
|
|
app.locals.favourites = [];
|
|
|
|
} else {
|
|
|
|
try {
|
|
|
|
app.locals.favourites = JSON.parse(data);
|
|
|
|
console.log('DB initialized', app.locals.favourites);
|
|
|
|
} catch(e) {
|
|
|
|
console.error(e);
|
|
|
|
app.locals.favourites = [];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initialize routers here
|
|
|
|
const routers = require('./routes/routers');
|
|
|
|
app.use('/', routers.root);
|
2019-10-21 20:17:21 +00:00
|
|
|
app.use('/favorites', routers.favourites);
|
|
|
|
app.use('/bookmarked', routers.bookmarked);
|
2019-10-21 16:56:21 +00:00
|
|
|
});
|
|
|
|
|
2019-10-28 07:35:04 +00:00
|
|
|
let writing = false;
|
|
|
|
app.locals.writeFavs = (done) => {
|
|
|
|
if (writing) {
|
|
|
|
setTimeout(() => app.locals.writeFavs(done), 100);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
writing = true;
|
|
|
|
fs.writeFile(__dirname + '/db.json', JSON.stringify(app.locals.favourites),
|
2019-10-21 16:56:21 +00:00
|
|
|
{ encoding: 'utf8' }, err => {
|
|
|
|
if (err) console.error(err);
|
2019-10-28 07:35:04 +00:00
|
|
|
writing = false;
|
|
|
|
done();
|
2019-10-21 16:56:21 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = app;
|