summary refs log tree commit diff stats
path: root/src/index.js
blob: fce4c09ddf9c3f8664a551aa41b947b0a425578f (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
'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')
  const post = posts.get(ctx.params.filename)
  post.body = Posts.render(post)
  await ctx.render('post', {
    post: post
  })
})

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)
  })
})

app.use(router.routes()).use(router.allowedMethods())

module.exports = app

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