From bdd6610208e9fe5971e6aed4378598092f2b9b5a Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Sat, 24 Jun 2017 16:34:47 +0200 Subject: refactor: separate app, responders --- src/responders.js | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/responders.js (limited to 'src/responders.js') diff --git a/src/responders.js b/src/responders.js new file mode 100644 index 0000000..1a9e8ce --- /dev/null +++ b/src/responders.js @@ -0,0 +1,76 @@ +'use strict' + +const fs = require('fs') +const rheo = require('rheo') + +const templateReader = template => () => + fs.createReadStream(`${__dirname}/templates/${template}.html`) +const templates = { + layout: templateReader('layout'), + home: templateReader('home'), + post: templateReader('post'), + taxon: templateReader('taxon') +} + +function setTitle (siteTitle, pageTitle) { + return rheo.template(function (s) { + return s + .inner('title', rheo((pageTitle ? ' · ' : '') + siteTitle)) + .inner('body header h1', rheo(siteTitle)) + }) +} + +function renderPostListItem (ctx) { + return function (template, [, post]) { + return template + .attribute('a', 'href', () => ctx.getURL('post', post.basename)) + .inner('a', () => rheo(post.data.get('title'))) + } +} + +function showPage (name) { + return function (els) { + return rheo(templates[name]()) + } +} + +module.exports = { + home (ctx, config, postsStream) { + ctx.set('Content-Type', 'text/html') + ctx.body = templates + .layout() + .pipe(rheo()) + .outer('main', showPage('home')) + .inner('.posts', function (postsTemplate) { + return postsStream.pipe(postsTemplate.map(renderPostListItem(ctx))) + }) + .pipe(setTitle(config.site.title)) + .render() + }, + + post (ctx, config, post) { + ctx.set('Content-Type', 'text/html') + ctx.body = templates + .layout() + .pipe(rheo()) + .inner('main', showPage('post')) + .inner('article h1', rheo(post.data.get('title'))) + .inner('article main', rheo(post.body)) + .pipe(setTitle(config.site.title, post.data.get('title'))) + .render() + }, + + taxon (ctx, config, taxonItems) { + ctx.set('Content-Type', 'text/html') + ctx.body = templates + .layout() + .pipe(rheo()) + .inner('main', showPage('taxon')) + .inner('h1', rheo(config.site.title)) + .inner('.posts', function (postsTemplate) { + return taxonItems.pipe(postsTemplate.map(renderPostListItem(ctx))) + }) + .pipe(setTitle(config.site.title)) + .render() + } +} -- cgit 1.4.1