// post.js // Copyright (C) 2021 Digital Telepresence, LLC // License: Apache-2.0 'use strict'; const DTP_COMPONENT_NAME = 'post'; const express = require('express'); const { SiteController, SiteError } = require('../../lib/site-lib'); class PostController extends SiteController { constructor (dtp) { super(dtp, DTP_COMPONENT_NAME); } async start ( ) { const { dtp } = this; const { limiter: limiterService } = dtp.services; const router = express.Router(); dtp.app.use('/post', router); router.use(this.dtp.services.gabTV.channelMiddleware('mrjoeprich')); router.use(async (req, res, next) => { res.locals.currentView = 'home'; return next(); }); router.param('postSlug', this.populatePostSlug.bind(this)); router.get('/:postSlug', limiterService.create(limiterService.config.post.getView), this.getView.bind(this), ); router.get('/', limiterService.create(limiterService.config.post.getIndex), this.getIndex.bind(this), ); } async populatePostYear (req, res, next, postYear) { try { res.locals.postYear = parseInt(postYear, 10); if (!res.locals.postYear || isNaN(res.locals.postYear)) { throw new Error('Invalid post year'); } return next(); } catch (error) { this.log.error('failed to populate post year', { postYear, error }); return next(error); } } async populatePostMonth (req, res, next, postMonth) { try { res.locals.postMonth = parseInt(postMonth, 10); if (!res.locals.postMonth || isNaN(res.locals.postMonth) || (postMonth < 1) || (postMonth > 12)) { throw new Error('Invalid post month'); } return next(); } catch (error) { this.log.error('failed to populate post month', { postMonth, error }); return next(error); } } async populatePostSlug (req, res, next, postSlug) { const { post: postService } = this.dtp.services; try { res.locals.post = await postService.getBySlug(postSlug); if (!res.locals.post) { throw new SiteError(404, 'Post not found'); } return next(); } catch (error) { this.log.error('failed to populate postSlug', { postSlug, error }); return next(error); } } async getView (req, res) { res.render('post/view'); } async getIndex (req, res, next) { const { post: postService } = this.dtp.services; try { res.locals.pagination = this.getPaginationParameters(req, 20); res.locals.posts = await postService.getPosts(res.locals.pagination); res.render('post/index'); } catch (error) { return next(error); } } } module.exports = async (dtp) => { let controller = new PostController(dtp); return controller; };