-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
82 lines (63 loc) · 1.3 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
73
74
75
76
77
78
79
80
81
82
/**
* Module dependencies.
*/
const path = require('path');
const logger = require('koa-logger');
const Router = require('koa-router');
const views = require('koa-views');
const bodyParser = require('koa-bodyparser');
const Koa = require('koa');
const app = module.exports = new Koa();
const router = new Router();
// "database"
var posts = [];
// middleware
app.use(bodyParser());
app.use(logger());
// route middleware
router.get('/', list);
router.get('/post/new', add);
router.get('/post/:id', show);
router.post('/post', create);
app
.use(views(path.join(__dirname, 'views'), {
map: {
html: 'swig'
}
}))
.use(router.routes())
.use(router.allowedMethods());
/**
* 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) {
var post = posts[ctx.params.id];
if (!post) ctx.throw(404, 'invalid post id');
await ctx.render('show', { post: post });
}
/**
* Create a post.
*/
async function create (ctx) {
var post = await ctx.request.body;
var id = posts.push(post) - 1;
post.created_at = new Date();
post.id = id;
ctx.redirect('/');
}
// listen
if (!module.parent) app.listen(3000);