all repos — archive/homestead @ 1f2a6245ab1e503dee017ab617aaeda816ecb383

My future indieweb platform

feat: add tags endpoint
Alan Pearce alan@alanpearce.eu
Sun, 18 Jun 2017 14:12:25 +0200
commit

1f2a6245ab1e503dee017ab617aaeda816ecb383

parent

69af7f12ec17f0aba65b0e23ef4045ee28f2dac8

M src/index.jssrc/index.js
@@ -29,6 +29,22 @@ post: posts.get(ctx.params.filename)   })
 })
 
+const tags = 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]))
+    }
+  }
+}
+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)
+  })
+})
+
 app.use(router.routes()).use(router.allowedMethods())
 
 module.exports = app
M src/modules/posts.jssrc/modules/posts.js
@@ -24,12 +24,14 @@ }   return meta
 }
 
-function get (filename) {
-  return canonicaliseMetadata(matter.read(filename, grayMatterOptions))
-}
-
 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) {
A src/views/tag.html
@@ -0,0 +1,3 @@+{% for post in posts %}
+  {{ post.data.get('title') }}
+{% endfor %}
M test/index.test.jstest/index.test.js
@@ -21,3 +21,11 @@ .expect(200)     .expect(/Lorem ipsum/)
     .then(() => t.pass())
 })
+
+test('tags', t => {
+  return request(app.listen())
+    .get('/tags/a')
+    .expect(200)
+    .expect(/This is a test/)
+    .then(() => t.pass())
+})
M test/modules/posts.test.jstest/modules/posts.test.js
@@ -11,8 +11,9 @@ description: 'Test file',       tags: ['a', 'b']
     })
   )
-  const meta = posts.get(path.resolve(__dirname, '../data/testfile.md'))
-  t.deepEqual(meta.data, expected)
+  const post = posts.get(path.resolve(__dirname, '../data/testfile.md'))
+  t.deepEqual(post.data, expected)
+  t.is(post.basename, 'testfile', 'must include basename')
 })
 
 test('getFolder', t => {