feat: add tags endpoint
Alan Pearce alan@alanpearce.eu
Sun, 18 Jun 2017 14:12:25 +0200
5 files changed, 36 insertions(+), 6 deletions(-)
M src/index.js → src/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.js → src/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.js → test/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.js → test/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 => {