/*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 eventRenderPage = (page) => { console.log('+++ eventRenderPage'); doRenderPage(page) }; var doRenderPage = (page) => { console.log('+ doRenderPage'); var compiledhtml, _page = $U.unDashObject(page); var htmlfile = __dirname + '/static/' + _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) { res.send({ pages: [] }); }); pagesRouter.post('/', function(req, res) { console.log(util.inspect(req.body.data)); dbPages.addNewPage(req.body.data) .then(function(data) { let response = { data: data }; eventHandler.emit('renderPage',data.attributes); console.log('Finalising...'); console.log(response); res.status(200).send(response); }) .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); };