summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--config/default.toml7
-rw-r--r--src/index.js21
-rw-r--r--src/modules/posts.js24
-rw-r--r--test/index.test.js2
4 files changed, 39 insertions, 15 deletions
diff --git a/config/default.toml b/config/default.toml
index 3026849..9047385 100644
--- a/config/default.toml
+++ b/config/default.toml
@@ -2,4 +2,9 @@
 port = 3000
 
 [posts]
-folder = "../posts"
\ No newline at end of file
+folder = "../posts"
+
+[taxonomies]
+tag = "tags"
+category = "categories"
+
diff --git a/src/index.js b/src/index.js
index 6df1530..52bdff0 100644
--- a/src/index.js
+++ b/src/index.js
@@ -37,14 +37,21 @@ router.get('/post/:filename', async function (ctx) {
   })
 })
 
-const tags = Posts.toTags(posts)
-router.get('/tags/:tag', async function (ctx) {
-  ctx.assert(tags.has(ctx.params.tag), 404, 'Tag not found')
-  await ctx.render('tag', {
-    tag: ctx.params.tag,
-    posts: tags.get(ctx.params.tag)
+const taxonomies = Posts.taxonomise(config.taxonomies, posts)
+for (let [term, items] of taxonomies) {
+  router.get(`/${term}/:value`, async function (ctx) {
+    const value = ctx.params.value
+    ctx.assert(
+      items.has(ctx.params.value),
+      404,
+      `Could not find ${term} ${value}`
+    )
+    await ctx.render('tag', {
+      [term]: value,
+      posts: items.get(ctx.params.value)
+    })
   })
-})
+}
 
 app.use(router.routes()).use(router.allowedMethods())
 
diff --git a/src/modules/posts.js b/src/modules/posts.js
index cba2372..cf2d80e 100644
--- a/src/modules/posts.js
+++ b/src/modules/posts.js
@@ -56,21 +56,33 @@ function getFolder (folder) {
   )
 }
 
-function toTags (posts) {
-  const tags = new Map()
+function taxonomise (taxonomies, posts) {
+  const taxons = new Map(Object.keys(taxonomies).map(t => [t, new Map()]))
+
   for (let [, post] of posts) {
-    if (post.data.has('tags')) {
-      for (let tag of post.data.get('tags')) {
-        tags.set(tag, (tags.get(tag) || []).concat([post]))
+    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 tags
+
+  return taxons
+}
+
+function toTags (posts) {
+  return taxonomise({ tag: 'tags' }, posts).get('tag')
 }
 
 module.exports = {
   get,
   getFolder,
   toTags,
+  taxonomise,
   render
 }
diff --git a/test/index.test.js b/test/index.test.js
index 926c5d4..5b5e991 100644
--- a/test/index.test.js
+++ b/test/index.test.js
@@ -26,7 +26,7 @@ test('post', t => {
 
 test('tags', t => {
   return request(app.listen())
-    .get('/tags/a')
+    .get('/tag/a')
     .expect(200)
     .expect(/This is a test/)
     .then(() => t.pass())