From 69af7f12ec17f0aba65b0e23ef4045ee28f2dac8 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Sun, 18 Jun 2017 13:36:29 +0200 Subject: feat: add single post endpoint --- src/index.js | 12 ++++++++++-- src/modules/posts.js | 12 +++++++++++- src/views/index.html | 2 +- src/views/post.html | 3 +++ 4 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 src/views/post.html (limited to 'src') diff --git a/src/index.js b/src/index.js index 3d25faa..f691930 100644 --- a/src/index.js +++ b/src/index.js @@ -15,9 +15,17 @@ const posts = Posts.getFolder(process.env.POST_DIR) app.use(view(`${__dirname}/views`)) -router.get('/', async function (ctx, next) { +const postsArray = Array.from(posts.entries()) +router.get('/', async function (ctx) { await ctx.render('index', { - posts + posts: postsArray + }) +}) + +router.get('/post/:filename', async function (ctx) { + ctx.assert(posts.has(ctx.params.filename), 404, 'Post not found') + await ctx.render('post', { + post: posts.get(ctx.params.filename) }) }) diff --git a/src/modules/posts.js b/src/modules/posts.js index 26db63d..2d831af 100644 --- a/src/modules/posts.js +++ b/src/modules/posts.js @@ -28,8 +28,18 @@ function get (filename) { return canonicaliseMetadata(matter.read(filename, grayMatterOptions)) } +function getTitle (file) { + return path.basename(file.path, path.extname(file.path)) +} + function getFolder (folder) { - return fs.readdirSync(folder).map(f => path.resolve(folder, f)).map(get) + return new Map( + fs + .readdirSync(folder) + .map(f => path.resolve(folder, f)) + .map(get) + .map(f => [getTitle(f), f]) + ) } module.exports = { diff --git a/src/views/index.html b/src/views/index.html index 0e900e6..dcc142c 100644 --- a/src/views/index.html +++ b/src/views/index.html @@ -1,5 +1,5 @@ hello world -{% for post in posts %} +{% for filename, post in posts %} {{ post.data.get('title') }} {% endfor %} diff --git a/src/views/post.html b/src/views/post.html new file mode 100644 index 0000000..fcc4dbd --- /dev/null +++ b/src/views/post.html @@ -0,0 +1,3 @@ +{{ post.data.title }} + +{{ post.content }} -- cgit 1.4.1