/** File which renders the edit form for the posts and processes * the post data generated by edit forms. * * @type {Promise|*} */ const Promise = require('promise'); const qs = require('querystring'); const sql = require('../utils/sql'); /** * Displays a single row in the posts view * * @param post */ const renderPostRow = function(post) { return "" + "" + post.category_id + "" + "" + post.name + "" + "" + post.picture_url + "" + "" + post.published + "" + "
\n" + "\n" + ""+ "
" + ""; }; /** * Displays all the posts in a table */ const postsTable = function() { var html = "
" + "

Posts

" + "
" + "" + "" + ""; return new Promise(function(resolve, reject) { sql.getAllPosts().then(function(posts) { var postPromises = []; posts.forEach(function(post) { postPromises.push(renderPostRow(post)); }); Promise.all(postPromises).then(function(htmls) { resolve(html + htmls.join('') + "
Category #NameHeader PictureDateEdit

"); }).catch(function(error) { reject(error); }); }).catch(function(error) { reject(error); }) }); }; /** * Displays the edit form for edit posts * @param post_id */ const displayRenderForm = function(post_id) { return new Promise(function(resolve, reject) { sql.getPostById(post_id).then(function(post) { var html = "
"+ "

Edit Post

"+ "
"+ "
\n" + " \n" + " \n" + "
"+ "
\n" + " \n" + " \n" + "
"+ "
\n" + " \n" + " \n" + "
"+ "
\n" + " \n" + " \n" + "
"+ "
"+ ""+ "
"+ "

"; resolve(html); }).catch(function(error) { reject(error); }); }); }; /** * Detects if the post data came from the edit form in posts table or edit post * in the edit post form. Based on this, this function will call one of two functions * @param postData */ const processPost = function(postData) { return new Promise(function(resolve, reject) { var postParsed = qs.parse(postData); if(postParsed.edit_post) { //display edit form displayRenderForm(postParsed.edit_post).then(function(html) { resolve(html); }).catch(function(error) { reject(error); }); } else if(postParsed.edit_post_2) { sql.editPost(postParsed).then(function(html) { resolve(html); }).catch(function(error) { reject(error); }); } else { resolve(""); } }); }; module.exports= { /** * Method which calls helper functions which processes post data for editing posts * and calls a function which displays all the posts in a table * @param postData */ main: function(postData) { return new Promise(function(resolve, reject) { Promise.all([processPost(postData), postsTable()]).then(function(html) { resolve("
" + html.join('')); }).catch(function(error) { console.log("error in edit post.js"); reject(error); }) }); } };