studyNotes
studyNotes copied to clipboard
koa开课前预习资料一
预习工作
安装软件
- Node.js http://nodejs.org/
- MongoDB http://mongodb.org/
- VSCode https://code.visualstudio.com/download
阅读文档
https://github.com/17koa/koa-guide
看一下Koa 2 帅帅的代码
restful api
/**
* Auto generate RESTful url routes.
*
* URL routes:
*
* GET /users[/] => user.list()
* GET /users/new => user.new()
* GET /users/:id => user.show()
* GET /users/:id/edit => user.edit()
* POST /users[/] => user.create()
* PATCH /users/:id => user.update()
* DELETE /users/:id => user.destroy()
*
*/
看起来很爽有木有?
目录结构

中间件
Koa 2.x最常见的modern中间件
exports.list = (ctx, next) => {
console.log(ctx.method + ' /users => list, query: ' + JSON.stringify(ctx.query));
return User.getAllAsync().then(( users)=>{
return ctx.render('users/index', {
users : users
})
}).catch((err)=>{
return ctx.api_error(err);
});
};
只要懂promise/a+规范,就能搞定,所以你以前玩express的经验,还是会非常有用呢~
Koa 2.x中使用generator
exports.list = function *(ctx, next) {
console.log(ctx.method + ' /students => list, query: ' + JSON.stringify(ctx.query));
let students = yield Student.getAllAsync();
yield ctx.render('students/index', {
students : students
})
};
有木有同步的感觉?
let students = yield Student.getAllAsync();
本来从数据库里获取所有学生信息是异步的操作,但是yield把它掰弯成同步的,有木有很爽?
实际上,它也是co包过的,这样更便于处理err
router.get('/list', (ctx, next) => {
return co.wrap($.list)(ctx, next).catch(err => {
return ctx.api_error(err);
})
});
代码就这么精简
Koa 2.x中使用async/await
exports.list = async (ctx, next) => {
console.log(ctx.method + ' /students => list, query: ' + JSON.stringify(ctx.query));
try {
let students = await Student.getAllAsync();
await ctx.render('students/index', {
students : students
})
} catch (err) {
return ctx.api_error(err);
}
};
它和generator其实没有太多区别,一样简单、命令,一通百通。
性感的ava测试
// * GET /users[/] => user.list()
test('GET /' + model, function * (t) {
var res = yield superkoa('../../app.js')
.get('/' + model)
t.is(200, res.status)
t.regex(res.text, /table/g)
})
测试也成了同步的感觉,有木有爽爽哒?
来个更复杂的原子性测试
// * GET /users/:id => user.show()
test('GET /' + model + '/:id show', function * (t) {
var res1 = yield superkoa('../../app.js')
.post('/api/' + model)
.send(mockUser)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
user = res1.body.user
var res = yield superkoa('../../app.js')
.get('/' + model + '/' + user._id)
t.is(200, res.status)
t.regex(res.text, /Edit/)
})
想要测试展示,就要先创建,每一步都是同步的,是不是代码逻辑看起来更清楚?