summary refs log tree commit diff stats
path: root/src/index.js
blob: e811be055f0db805ab80e640cf111e2f20a61072 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'use strict'

const PORT = process.env.PORT || 3000

const Koa = require('koa')
const app = new Koa()

const Router = require('koa-router')
const router = new Router()

const view = require('koa-nunjucks-next')

const Posts = require('./modules/posts.js')
const posts = Posts.getFolder(process.env.POST_DIR)

app.use(view(`${__dirname}/views`))

const postsArray = Array.from(posts.entries())
router.get('/', async function (ctx) {
  await ctx.render('index', {
    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)
  })
})

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

if (require.main === module) {
  app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`)
  })
}