fipamo/brain/api/v1/pages.js

126 lines
2.7 KiB
JavaScript
Raw Normal View History

import Book from '../../data/Book';
2019-11-23 17:40:51 +01:00
import * as DataEvent from '../../../src/com/events/DataEvent';
const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs-extra');
const moment = require('moment');
const book = new Book();
const uploadPath =
'./public/assets/images/blog/' + moment().format('YYYY') + '/' + moment().format('MM');
fs.ensureDir(uploadPath, () => {
// dir has now been created, including the directory it is to be placed in
});
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, uploadPath);
},
filename: function(req, file, cb) {
var splice = file.originalname.split(':');
cb(null, splice[0]);
}
});
var feature_upload = multer({
storage: storage
}).array('feature_image');
var post_upload = multer({
storage: storage
}).array('post_image');
/***
Retrieve Pages
*/
router.get('/', (req, res) => {
book.getPage().then(result => {
res.json(result);
});
});
/***
Update Page
*/
router.post('/write/:task?', feature_upload, (req, res) => {
var feature = '';
if (req.files.length > 0) {
var path = req.files[0].path;
feature = '/' + path.substring(7, path.length);
} else {
var url = req.body.feature_image;
url != null || url != undefined || url != ''
? (feature = url.substring(21, url.length))
: (feature = '');
}
var pageWrite =
'---\n' +
'id: ' +
req.body.page_id +
'\n' +
'uuid: ' +
req.body.page_uuid +
'\n' +
'title: ' +
req.body.title +
'\n' +
'feature: ' +
feature +
'\n' +
'layout: ' +
'page' +
'\n' +
'tags: ' +
req.body.tags +
'\n' +
'author: ' +
req.session.user.handle +
'\n' +
'created: ' +
moment(req.body.created).format() +
'\n' +
'updated: ' +
moment(Date.now()).format() +
'\n' +
'menu: ' +
req.body.pinToMenu +
'\n' +
'featured: ' +
req.body.featureStatus +
'\n' +
'published: ' +
req.body.publishedStatus +
'\n' +
'slug: ' +
req.body.slug +
'\n' +
'---\n\n' +
req.body.content;
fs.writeFile('content/pages/' + req.body.slug + '.md', pageWrite, err => {
// throws an error, you could also catch it here
if (err) res.json({ type: DataEvent.PAGE_ERROR, message: err });
// success case, the file was saved
if (req.params.task === 'new') {
res.json({
type: DataEvent.PAGE_ADDED,
message: 'New Page Created',
id: req.body.page_uuid
});
} else {
res.json({ type: DataEvent.PAGE_UPDATED, message: 'Page saved, boss' });
}
});
});
router.post('/add-post-image', post_upload, function(req, res) {
//console.log(req.body);
var image = req.files[0].path;
return res.json({
type: DataEvent.POST_IMAGE_ADDED,
message: 'Added Image',
url: '/' + image.substr(7, image.length)
});
});
module.exports = router;