我正在使用koa-router来定义REST api。
我有一条允许客户端修补数据的路由,为此我希望只回复: -
确定 - 数据修补无错误
或
不行 - 发生错误。
(a[aeiou]{2}|i[aeiou]{2}|i[aeiou]{2}|o[aeiou]{2}|u[aeiou]{2})
是否有比以上更标准的方式?
答案 0 :(得分:1)
不要产生简单的物体。只有在通过yieldable(promise,thunk,generator ...)分配一个或多个属性时才生成对象。
考虑返回更新的项目以防止需要额外的api调用。
我正在使用 this.throw()
。
router.patch('/api/data', function *(next) {
if (_.has(this.query, 'id')) {
this.status = 200;
// don't yield...
this.body = {status: 200, body: 'OK'};
// consider returning the updated item to prevent the need to additional
// api calls
this.body = yield model.update(this.query.id, ...)
} else {
this.throw(304, 'expecting id', {custom: 'properties here'});
}
});
答案 1 :(得分:1)
要温和地改进@James Moore的回答,如果this.assert(expression, [status], [message])
不真实,您也可以使用expression
提早缩短路线。
我已将其代码转换为演示:
router.patch('/api/data', function*(next) {
this.assert(_.has(this.query, 'id'), 304, JSON.stringify({ status: 304, body: 'expecting id' })));
this.body = JSON.stringify({ status: 200, body: 'OK' });
});