From dd819c45b58088f9a98384ab237268d865836fe0 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Sat, 24 Jun 2017 22:05:18 +0200 Subject: refactor: re-architect to be closer to ADR --- src/domain/posts.js | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/domain/posts.js (limited to 'src/domain') diff --git a/src/domain/posts.js b/src/domain/posts.js new file mode 100644 index 0000000..14bc7cc --- /dev/null +++ b/src/domain/posts.js @@ -0,0 +1,74 @@ +'use strict' + +const fs = require('fs') +const path = require('path') +const matter = require('gray-matter') + +const grayMatterOptions = { + lang: 'toml', + delims: '+++' +} + +function* lowercaseKeys (iterator) { + for (let [k, v] of iterator) { + yield [String(k).toLowerCase(), v] + } +} + +function canonicaliseMetadata (meta) { + if (meta.data) { + meta.data = new Map(lowercaseKeys(Object.entries(meta.data))) + } else { + meta.data = new Map() + } + return meta +} + +function getTitle (file) { + return path.basename(file.path, path.extname(file.path)) +} + +function get (filename) { + const fileMatter = matter.read(filename, grayMatterOptions) + fileMatter.basename = getTitle(fileMatter) + return canonicaliseMetadata(fileMatter) +} + +function getFolder (folder) { + return new Map( + fs + .readdirSync(folder) + .map(f => path.resolve(folder, f)) + .map(get) + .map(f => [getTitle(f), f]) + ) +} + +function taxonomise (taxonomies, posts) { + const taxons = new Map(Object.keys(taxonomies).map(t => [t, new Map()])) + + for (let [, post] of posts) { + for (let [singularName, pluralName] of Object.entries(taxonomies)) { + if (post.data.has(pluralName)) { + for (let term of post.data.get(pluralName)) { + const current = taxons.get(singularName).get(term) + taxons + .get(singularName) + .set(term, current ? current.concat(post) : [post]) + } + } + } + } + + return taxons +} + +module.exports = function (config) { + const posts = getFolder(config.folder) + const taxonomies = taxonomise(config.taxonomies, posts) + return { + posts, + taxonomies, + get + } +} -- cgit 1.4.1