The controller directory holds the controller class, and the controller class define controller by decorator Controller from require('koa-cola/client'). and we can define the router and view by decorators as well, so We can design different controllers according to different production needs.
Controller that provides api interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { Controller, Get, Post, Body } = require('koa-cola/client');
@Controller('')
exportdefaultclass{
@Get('/todo/list')
async getTodoList() {
returnawait app.models.todo.find({});
}
@Post('/todo/save')
async saveTodo(@Body() body) {
returnawait app.models.todo.save(body);
}
}
Return fixed data format by return of router
1
2
3
4
5
6
7
8
/**
data format:
[todoItem, ...]
*/
@Get('/todo/list')
async getTodoList() {
returnawait app.models.todo.find({});
}
return a pre-define wrapper data format by using Response decorator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const Ok = functionOk(ctx, data){
ctx.status = 200;
if(data){
ctx.body = {
code : 200,
result : data
};
}
}
/**
return data format:
{
code : 200,
result : [todoItem, ...]
}
*/
@Get('/todo/list')
@Response(Ok)
async getTodoList() {
returnawait app.models.todo.find({});
}
Using Use decorator as middleware of router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
functionisLogin(ctx, next){
if(ctx.state.user){
await next();
}else{
ctx.throw(401);
}
}
...
// Verify that the user is logged in, and return 401 if not