From eee42ab329eb2f84dc0eeee700b2d12a3863b455 Mon Sep 17 00:00:00 2001 From: mrjvs Date: Tue, 16 Oct 2018 15:20:06 +0200 Subject: [PATCH] refactored helpers into seperate files --- helpers/{common.js => api.js} | 23 +--------- helpers/util.js | 15 +++++++ middleware/admin-authentication.js | 4 +- models/blog-post.js | 5 ++- package-lock.json | 5 +++ package.json | 1 + routes/admin.js | 67 +++++++++++++++--------------- routes/blog.js | 19 +++++---- routes/contact.js | 10 ++--- routes/progress.js | 9 ++-- server.js | 4 +- 11 files changed, 83 insertions(+), 79 deletions(-) rename helpers/{common.js => api.js} (72%) create mode 100644 helpers/util.js diff --git a/helpers/common.js b/helpers/api.js similarity index 72% rename from helpers/common.js rename to helpers/api.js index 6143096..b98c8c6 100644 --- a/helpers/common.js +++ b/helpers/api.js @@ -1,15 +1,3 @@ -/* - -common.js - -common page functionality. - -*/ - -// shows 404 template. -function sendDefault404(res) { - res.status(404).send('404'); -} - // use for any api return. it has basic layout used for every return. function sendApiReturn(res, data, errors) { res.status(200).json( @@ -63,19 +51,10 @@ function sendApiError(res, code, errors) { }); } -// convert date to string -function convertDateToString(date) { - return date.getUTCFullYear() + '-' + - ('0' + (date.getUTCMonth()+1)).slice(-2) + '-' + - ('0' + date.getUTCDate()).slice(-2); -} - module.exports = { - sendDefault404, sendApiReturn, sendApi404, sendApiGenericError, sendApiError, - sendApiAuthError, - convertDateToString + sendApiAuthError }; \ No newline at end of file diff --git a/helpers/util.js b/helpers/util.js new file mode 100644 index 0000000..00e8e3d --- /dev/null +++ b/helpers/util.js @@ -0,0 +1,15 @@ +/* + +util.js - +small commonly used utilities + +*/ + +// shows 404 template. +function sendDefault404(res) { + res.status(404).send('404'); +} + +module.exports = { + sendDefault404 +}; \ No newline at end of file diff --git a/middleware/admin-authentication.js b/middleware/admin-authentication.js index 4717352..160132e 100644 --- a/middleware/admin-authentication.js +++ b/middleware/admin-authentication.js @@ -6,14 +6,14 @@ Middleware file for authentication checking */ // imports -const common = require('../helpers/common'); +const apiHelper = require('../helpers/api'); // middleware to use if admin authentication is required function adminAuthenticationRequired(req, res, next) { if (req.isAuthenticated() && req.user.role && req.user.role === 'admin') { return next(); } else { - common.sendApiAuthError(res); + apiHelper.sendApiAuthError(res); } } diff --git a/models/blog-post.js b/models/blog-post.js index 1bf656e..4d966d1 100644 --- a/models/blog-post.js +++ b/models/blog-post.js @@ -10,6 +10,7 @@ const mongoose = require('mongoose'); const common = require('../helpers/common'); const postAuthor = require('./post-author').postAuthorModel; const showdown = require('showdown'); +const moment = require('moment'); const converter = new showdown.Converter(); converter.setFlavor('github'); @@ -43,7 +44,7 @@ const blogPostSchema = new mongoose.Schema({ date: { type: Date, default: () => { - return new Date(common.convertDateToString(new Date())); + return new Date(moment(new Date(), 'YYYY-MM-DD')); } }, category: { @@ -73,7 +74,7 @@ blogPostSchema.methods.getBlogPostShortTemplateReady = function() { return { content: this.short, title: this.name, - url: common.convertDateToString(this.meta.date) + '/' + this.meta.slug + url: moment(this.meta.date, 'YYYY-MM-DD') + '/' + this.meta.slug }; }; diff --git a/package-lock.json b/package-lock.json index c3a9751..205475e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1746,6 +1746,11 @@ } } }, + "moment": { + "version": "2.22.2", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.22.2.tgz", + "integrity": "sha1-PCV/mDn8DpP/UxSWMiOeuQeD/2Y=" + }, "mongodb": { "version": "3.1.6", "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.6.tgz", diff --git a/package.json b/package.json index c7b1948..fff669b 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "express": "^4.16.2", "express-handlebars": "^3.0.0", "express-session": "^1.15.6", + "moment": "^2.22.2", "mongoose": "^5.3.2", "mongoose-unique-validator": "^2.0.2", "passport": "^0.4.0", diff --git a/routes/admin.js b/routes/admin.js index 006733f..0853375 100644 --- a/routes/admin.js +++ b/routes/admin.js @@ -8,7 +8,8 @@ file for handling admin panel routes // imports const router = require('express').Router(); const passport = require('passport'); -const common = require('../helpers/common'); +const moment = require('moment'); +const apiHelper = require('../helpers/api'); const adminUserMiddleware = require('../middleware/admin-authentication'); const adminUser = require('../models/admin-user'); const blogPost = require('../models/blog-post'); @@ -39,7 +40,7 @@ router.get('/admin', (req, res) => { */ // TODO make login somehow display errors in correct format. router.post('/admin/api/v1/login', passport.authenticate('adminUserStrategy'), function (req, res) { - common.sendApiReturn(res, { + apiHelper.sendApiReturn(res, { username: req.user.username, role: req.user.role ? req.user.role : undefined }); @@ -66,7 +67,7 @@ router.post('/admin/api/v1/login', passport.authenticate('adminUserStrategy'), f router.post('/admin/api/v1/register', adminUserMiddleware.adminAuthenticationRequired, (req, res) => { if (!req.body) { // no post body - common.sendApiGenericError(res); + apiHelper.sendApiGenericError(res); return; } @@ -78,14 +79,14 @@ router.post('/admin/api/v1/register', adminUserMiddleware.adminAuthenticationReq newUser.save().then(() => { // successfull - common.sendApiReturn(res, { + apiHelper.sendApiReturn(res, { username: req.user.username, role: req.user.role ? req.user.role : undefined }); return; }).catch((rejection) => { // TODO format exception so it doesnt have a huge list of errors - common.sendApiError(res, 500, [rejection]); + apiHelper.sendApiError(res, 500, [rejection]); return; }); }); @@ -107,15 +108,15 @@ router.post('/admin/api/v1/register', adminUserMiddleware.adminAuthenticationReq */ router.post('/admin/api/v1/removeadmin', adminUserMiddleware.adminAuthenticationRequired, (req, res) => { if (!req.body) { - common.sendApiGenericError(res); + apiHelper.sendApiGenericError(res); return; } const { id } = req.body; adminUser.adminUserModel.findByIdAndDelete(id, (err) => { - if (err) return common.sendApiError(res, 500, [err]); + if (err) return apiHelper.sendApiError(res, 500, [err]); // successfull - common.sendApiReturn(res, {}); + apiHelper.sendApiReturn(res, {}); }); }); @@ -134,14 +135,14 @@ router.post('/admin/api/v1/removeadmin', adminUserMiddleware.adminAuthentication router.get('/admin/api/v1/listadmins', adminUserMiddleware.adminAuthenticationRequired, (req, res) => { adminUser.adminUserModel.find({}, (err, admins) => { // TODO format exception so it doesnt have a huge list of errors - if (err) return common.sendApiError(res, 500, [err]); + if (err) return apiHelper.sendApiError(res, 500, [err]); const output = []; for (let i = 0, l = admins.length; i < l; i++) { admins[i].password = undefined; output.push(admins[i]); } - common.sendApiReturn(res, { + apiHelper.sendApiReturn(res, { admins: output }); }); @@ -161,7 +162,7 @@ router.get('/admin/api/v1/listadmins', adminUserMiddleware.adminAuthenticationRe * } */ router.get('/admin/api/v1/check', adminUserMiddleware.authenticationOptional, (req, res) => { - common.sendApiReturn(res, { + apiHelper.sendApiReturn(res, { isAuthed: req.user ? true : false, role: req.user ? (req.user.role ? req.user.role : undefined) : undefined }); @@ -180,7 +181,7 @@ router.get('/admin/api/v1/check', adminUserMiddleware.authenticationOptional, (r */ router.get('/admin/api/v1/logout', adminUserMiddleware.adminAuthenticationRequired, (req, res) => { req.logout(); - common.sendApiReturn(res, {}); + apiHelper.sendApiReturn(res, {}); }); /* @@ -205,7 +206,7 @@ router.get('/admin/api/v1/logout', adminUserMiddleware.adminAuthenticationRequir */ router.post('/admin/api/v1/newpost', adminUserMiddleware.adminAuthenticationRequired, function (req, res) { - if (!req.body) return common.sendApiGenericError(res); + if (!req.body) return apiHelper.sendApiGenericError(res); const { content, title, author, category, short } = req.body; const newBlogPost = new blogPost.blogPostModel({ @@ -225,12 +226,12 @@ router.post('/admin/api/v1/newpost', adminUserMiddleware.adminAuthenticationRequ newBlogPost.save().then((post) => { // successfull - common.sendApiReturn(res, { - url: common.convertDateToString(post.meta.date) + '/' + post.meta.slug + apiHelper.sendApiReturn(res, { + url: moment(post.meta.date, 'YYYY-MM-DD') + '/' + post.meta.slug }); }).catch((rejection) => { // TODO format exception so it doesnt have a huge list of errors - common.sendApiError(res, 500, [rejection]); + apiHelper.sendApiError(res, 500, [rejection]); return; }); }); @@ -257,7 +258,7 @@ router.post('/admin/api/v1/newpost', adminUserMiddleware.adminAuthenticationRequ */ router.post('/admin/api/v1/editpost', adminUserMiddleware.adminAuthenticationRequired, function (req, res) { - if (!req.body) return common.sendApiGenericError(res); + if (!req.body) return apiHelper.sendApiGenericError(res); const { id, content, title, author, category, short } = req.body; blogPost.blogPostModel.findByIdAndUpdate(id, { @@ -267,9 +268,9 @@ router.post('/admin/api/v1/editpost', adminUserMiddleware.adminAuthenticationReq 'meta.author': author, 'meta.category': category }, (err, post) => { - if (err) return common.sendApiError(res, 500, [err]); - common.sendApiReturn(res, { - url: common.convertDateToString(post.meta.date) + '/' + post.meta.slug + if (err) return apiHelper.sendApiError(res, 500, [err]); + apiHelper.sendApiReturn(res, { + url: moment(post.meta.date, 'YYYY-MM-DD') + '/' + post.meta.slug }); }); }); @@ -293,7 +294,7 @@ router.post('/admin/api/v1/editpost', adminUserMiddleware.adminAuthenticationReq */ router.post('/admin/api/v1/newauthor', adminUserMiddleware.adminAuthenticationRequired, function (req, res) { - if (!req.body) return common.sendApiGenericError(res); + if (!req.body) return apiHelper.sendApiGenericError(res); const { name, description, image } = req.body; const newAuthor = new postAuthor.postAuthorModel({ @@ -304,12 +305,12 @@ router.post('/admin/api/v1/newauthor', adminUserMiddleware.adminAuthenticationRe newAuthor.save().then((author) => { // successfull - common.sendApiReturn(res, { + apiHelper.sendApiReturn(res, { id: author.id }); }).catch((rejection) => { // TODO format exception so it doesnt have a huge list of errors - common.sendApiError(res, 500, [rejection]); + apiHelper.sendApiError(res, 500, [rejection]); return; }); }); @@ -334,7 +335,7 @@ router.post('/admin/api/v1/newauthor', adminUserMiddleware.adminAuthenticationRe */ router.post('/admin/api/v1/editauthor', adminUserMiddleware.adminAuthenticationRequired, function (req, res) { - if (!req.body) return common.sendApiGenericError(res); + if (!req.body) return apiHelper.sendApiGenericError(res); const { id, name, description, image } = req.body; @@ -344,8 +345,8 @@ router.post('/admin/api/v1/editauthor', adminUserMiddleware.adminAuthenticationR image }, (err, author) => { // TODO format exception so it doesnt have a huge list of errors - if (err) return common.sendApiError(res, 500, [err]); - common.sendApiReturn(res, { + if (err) return apiHelper.sendApiError(res, 500, [err]); + apiHelper.sendApiReturn(res, { id: author.id }); }); @@ -370,7 +371,7 @@ router.post('/admin/api/v1/editauthor', adminUserMiddleware.adminAuthenticationR */ router.post('/admin/api/v1/newprogress', adminUserMiddleware.adminAuthenticationRequired, function (req, res) { - if (!req.body) return common.sendApiGenericError(res); + if (!req.body) return apiHelper.sendApiGenericError(res); const { title, description } = req.body; let { state } = req.body; @@ -391,12 +392,12 @@ router.post('/admin/api/v1/newprogress', adminUserMiddleware.adminAuthentication newProgress.save().then((progress) => { // successfull - common.sendApiReturn(res, { + apiHelper.sendApiReturn(res, { id: progress.id }); }).catch((rejection) => { // TODO format exception so it doesnt have a huge list of errors - common.sendApiError(res, 500, [rejection]); + apiHelper.sendApiError(res, 500, [rejection]); return; }); }); @@ -421,7 +422,7 @@ router.post('/admin/api/v1/newprogress', adminUserMiddleware.adminAuthentication */ router.post('/admin/api/v1/editprogress', adminUserMiddleware.adminAuthenticationRequired, function (req, res) { - if (!req.body) return common.sendApiGenericError(res); + if (!req.body) return apiHelper.sendApiGenericError(res); const { title, description, id } = req.body; let { state } = req.body; @@ -440,8 +441,8 @@ router.post('/admin/api/v1/editprogress', adminUserMiddleware.adminAuthenticatio isGame }, (err, progress) => { // TODO format exception so it doesnt have a huge list of errors - if (err) return common.sendApiError(res, 500, [err]); - common.sendApiReturn(res, { + if (err) return apiHelper.sendApiError(res, 500, [err]); + apiHelper.sendApiReturn(res, { id: progress.id }); }); @@ -449,7 +450,7 @@ router.post('/admin/api/v1/editprogress', adminUserMiddleware.adminAuthenticatio // configure api 404 router.use('/admin/api', (req, res) => { - common.sendApi404(res); + apiHelper.sendApi404(res); }); // export the router diff --git a/routes/blog.js b/routes/blog.js index f6f8095..273afe5 100644 --- a/routes/blog.js +++ b/routes/blog.js @@ -7,7 +7,8 @@ file for handling routes regarding blog posts. // imports const router = require('express').Router(); -const common = require('../helpers/common'); +const apiHelper = require('../helpers/api'); +const utilHelper = require('../helpers/util'); const blogPostModel = require('../models/blog-post').blogPostModel; const postAuthorModel = require('../models/post-author').postAuthorModel; @@ -20,12 +21,12 @@ router.get('/news/:date/:title', (req, res) => { // error exists or no post exists with the date and name if (err || !post) { console.log('error: ' + err + ' and post: ' + post); - return common.sendDefault404(res); + return utilHelper.sendDefault404(res); } // render blogpost post.getBlogPostTemplateReady((err, postTemplate) => { - if (err) return common.sendDefault404(res); + if (err) return utilHelper.sendDefault404(res); res.render('post', { post: postTemplate }); @@ -33,7 +34,7 @@ router.get('/news/:date/:title', (req, res) => { }); } else { // params are incorrect - common.sendDefault404(res); + utilHelper.sendDefault404(res); } }); @@ -41,7 +42,7 @@ router.get('/news/:date/:title', (req, res) => { router.get('/news', (req, res) => { blogPostModel.find({}).sort({'meta.date': 'desc'}).exec(function(err, posts) { if (err || !posts) { - return common.sendDefault404(res); + return utilHelper.sendDefault404(res); } const postCollection = []; @@ -70,8 +71,8 @@ router.get('/news', (req, res) => { router.get('/api/v1/listauthors', function (req, res) { postAuthorModel.find({}, (err, authors) => { // TODO format exception so it doesnt have a huge list of errors - if (err) return common.sendApiError(res, 500, [err]); - common.sendApiReturn(res, { + if (err) return apiHelper.sendApiError(res, 500, [err]); + apiHelper.sendApiReturn(res, { authorList: authors }); }); @@ -92,8 +93,8 @@ router.get('/api/v1/listauthors', function (req, res) { router.get('/api/v1/listblog', function (req, res) { blogPostModel.find({}, (err, posts) => { // TODO format exception so it doesnt have a huge list of errors - if (err) return common.sendApiError(res, 500, [err]); - common.sendApiReturn(res, { + if (err) return apiHelper.sendApiError(res, 500, [err]); + apiHelper.sendApiReturn(res, { postList: posts }); }); diff --git a/routes/contact.js b/routes/contact.js index f284f3f..627e4df 100644 --- a/routes/contact.js +++ b/routes/contact.js @@ -7,7 +7,7 @@ file for handling routes regarding contact // imports const router = require('express').Router(); -const common = require('../helpers/common'); +const apiHelper = require('../helpers/api'); const config = require('../config.json'); const https = require('https'); @@ -33,7 +33,7 @@ router.get('/contact', (req, res) => { * } */ router.post('/api/v1/sendmessage', function (req, res) { - if (!req.body) return common.sendApiGenericError(res); + if (!req.body) return apiHelper.sendApiGenericError(res); const { email, subject, message } = req.body; if (email && subject && message && message.length < 2000) { @@ -53,11 +53,11 @@ router.post('/api/v1/sendmessage', function (req, res) { 'Content-Length': postData.length } }, () => { - common.sendApiReturn(res, {}); + apiHelper.sendApiReturn(res, {}); }); request.on('error', (e) => { - common.sendApiGenericError(res); + apiHelper.sendApiGenericError(res); console.log('request errored' + e); }); @@ -65,7 +65,7 @@ router.post('/api/v1/sendmessage', function (req, res) { request.end(); } else { // TODO give more detailed response - return common.sendApiGenericError(res); + return apiHelper.sendApiGenericError(res); } }); diff --git a/routes/progress.js b/routes/progress.js index e6f4d0e..3ad5430 100644 --- a/routes/progress.js +++ b/routes/progress.js @@ -7,7 +7,8 @@ file for handling routes regarding progress // imports const router = require('express').Router(); -const common = require('../helpers/common'); +const apiHelper = require('../helpers/api'); +const utilHelper = require('../helpers/util'); const staticText = require('../static-text.json'); const progressListModel = require('../models/progress-list').progressListModel; @@ -15,7 +16,7 @@ const progressListModel = require('../models/progress-list').progressListModel; router.get('/progress', (req, res) => { progressListModel.find({}, (err, progress) => { - if (err) return common.sendDefault404(res); + if (err) return apiHelper.sendDefault404(res); const games = progress.filter(i => i.isGame); const backends = progress.filter(i => !i.isGame); @@ -43,8 +44,8 @@ router.get('/progress', (req, res) => { router.get('/api/v1/listprogress', function (req, res) { progressListModel.find({}, (err, progress) => { // TODO format exception so it doesnt have a huge list of errors - if (err) return common.sendApiError(res, 500, [err]); - common.sendApiReturn(res, { + if (err) return apiHelper.sendApiError(res, 500, [err]); + apiHelper.sendApiReturn(res, { progressList: progress }); }); diff --git a/server.js b/server.js index dfad964..a934f94 100644 --- a/server.js +++ b/server.js @@ -13,7 +13,7 @@ const mongoStore = require('connect-mongo')(session); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const config = require('./config.json'); -const common = require('./helpers/common'); +const utilHelper = require('./helpers/util'); const passportconfig = require('./passport.config.js'); // setup console colors @@ -73,7 +73,7 @@ app.use('/', locations.posts); app.use('/', locations.admin); app.use('/', locations.progress); app.use((req, res) => { - common.sendDefault404(res); + utilHelper.sendDefault404(res); }); // TODO improve error handling