最好的做法koa路由响应好,不好

时间:2015-10-04 13:00:12

标签: response router koa

我正在使用koa-router来定义REST api。

我有一条允许客户端修补数据的路由,为此我希望只回复: -

确定 - 数据修补无错误

不行 - 发生错误。

(a[aeiou]{2}|i[aeiou]{2}|i[aeiou]{2}|o[aeiou]{2}|u[aeiou]{2})

是否有比以上更标准的方式?

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' });
});