-
Notifications
You must be signed in to change notification settings - Fork 741
/
Copy pathapp.js
72 lines (51 loc) · 1.1 KB
/
app.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const render = require('./lib/render');
const logger = require('koa-logger');
const router = require('@koa/router')();
const koaBody = require('koa-body');
const Koa = require('koa');
const app = module.exports = new Koa();
// "database"
const posts = [];
// middleware
app.use(logger());
app.use(render);
app.use(koaBody());
// route definitions
router.get('/', list)
.get('/post/new', add)
.get('/post/:id', show)
.post('/post', create);
app.use(router.routes());
/**
* Post listing.
*/
async function list(ctx) {
await ctx.render('list', { posts: posts });
}
/**
* Show creation form.
*/
async function add(ctx) {
await ctx.render('new');
}
/**
* Show post :id.
*/
async function show(ctx) {
const id = ctx.params.id;
const post = posts[id];
if (!post) ctx.throw(404, 'invalid post id');
await ctx.render('show', { post: post });
}
/**
* Create a post.
*/
async function create(ctx) {
const post = ctx.request.body;
const id = posts.push(post) - 1;
post.created_at = new Date();
post.id = id;
ctx.redirect('/');
}
// listen
if (!module.parent) app.listen(3000);