/*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 templates = { basic: {path: __dirname + '/jade/type0.jade', compiled: null} }; var exportPath = __dirname + '/../static/'; var doRenderPage = (page) => { var compiledhtml; var _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); }; var eventRenderPage = (page) => { doRenderPage(page); }; eventHandler.on('renderPage', eventRenderPage); module.exports = function(app) { var express = require('express'); var pagesRouter = express.Router(); pagesRouter.get('/', function(req, res) { dbPages.getFullPageList() .then(function(data) { const response = { data: data }; res.status(200).send(response); }).catch((err)=> { console.error(err); res.status(401).end(); }); }); pagesRouter.get('/list', function(req, res) { dbPages.getPageList() .then(function(data) { res.render('pages', {data: data}); }).catch((err)=> { console.error(err); res.status(401).end(); }); }); pagesRouter.post('/', function(req, res) { dbPages.addNewPage(req.body.data) .then(function(data) { let response = { data: data }; res.status(200).send(response); eventHandler.emit('renderPage', data.attributes); }) .catch((err)=> { console.error(err); res.status(401).end(); }); }); pagesRouter.patch('/', function(req, res) { dbPages.addNewPage(req.body.data) .then(function(data) { let response = { data: data }; 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 } }); }); app.use('/api/pages', require('body-parser').json({type: 'application/vnd.api+json'})); app.use('/api/pages', pagesRouter); };