obrand-admin-server/server/app/pages.js
Martin Donnelly 40a8337ab3 Server up and running and serving all the previous mocked stuff.
Also now serving api/pages as a list page and viewer.
2016-03-31 14:24:21 +01:00

141 lines
3.1 KiB
JavaScript

/*jshint node:true*/
'use strict';
var db = require('../units/db-connector').dbConnection;
var dbPages = require('../units/db-pages')(db);
var $U = require('md-utils');
var Events = require('events');
var jade = require('jade');
var fs = require('fs');
var eventHandler = new Events();
var util = require('util');
var templates = {
basic: {path: __dirname + '/jade/type0.jade', compiled: null}
};
var exportPath = __dirname + '/../static/';
var eventRenderPage = (page) => {
console.log('+++ eventRenderPage');
doRenderPage(page);
};
var doRenderPage = (page) => {
console.log('+ doRenderPage');
var compiledhtml, _page = $U.unDashObject(page);
var htmlfile = exportPath + _page.pid + '.html';
if (templates.basic.compiled === null) {
templates.basic.compiled = jade.compileFile(templates.basic.path);
}
compiledhtml = templates.basic.compiled(_page);
fs.writeFileSync(htmlfile, compiledhtml);
console.log('- doRenderPage');
};
eventHandler.on('renderPage', eventRenderPage);
module.exports = function(app) {
var express = require('express');
var pagesRouter = express.Router();
pagesRouter.get('/', function(req, res) {
dbPages.getPageList()
.then(function(data) {
console.log(util.inspect(data));
res.render('pages', {data:data});
}).catch((err)=> {
console.error(err);
res.status(401).end();
});
});
pagesRouter.post('/', function(req, res) {
console.log(util.inspect(req.body.data));
dbPages.addNewPage(req.body.data)
.then(function(data) {
let response = {
data: data
};
console.log('Finalising...');
res.status(200).send(response);
eventHandler.emit('renderPage',data.attributes);
})
.catch((err)=> {
console.error(err);
res.status(401).end();
});
});
pagesRouter.patch('/', function(req, res) {
console.log(util.inspect(req.body.data));
dbPages.addNewPage(req.body.data)
.then(function(data) {
let response = {
data: data
};
console.log('Finalising...');
res.status(200).send(response);
eventHandler.emit('renderPage',data.attributes);
})
.catch((err)=> {
console.error(err);
res.status(401).end();
});
});
pagesRouter.get('/:id', function(req, res) {
res.send({
pages: {
id: req.params.id
}
});
});
pagesRouter.put('/:id', function(req, res) {
res.send({
pages: {
id: req.params.id
}
});
});
pagesRouter.delete('/:id', function(req, res) {
res.status(204).end();
});
// The POST and PUT call will not contain a request body
// because the body-parser is not included by default.
// To use req.body, run:
// Npm install --save-dev body-parser
app.use('/api/pages', require('body-parser').json({type: 'application/vnd.api+json'}));
// After installing, you need to `use` the body-parser for
// this mock uncommenting the following line:
//
//App.use('/api/pages', require('body-parser').json());
app.use('/api/pages', pagesRouter);
};