mfc
mfc

Reputation: 3026

best practise koa routing responses for ok and not ok

I'm using koa-router to define an REST api.

I have a route to allow clients to patch data, for this I expect to only response with :-

OK - data patched without error

or

NOT OK - error occurred.

router.patch('/api/data', function *(next) {
    if (_.has(this.query, 'id')) {
        // do data patch
        this.status = 200;
        this.body = yield {status: 200, body: 'OK'};
    } else {
        this.status = 304;
        this.body = yield {status: 304, body: 'expecting id};
    }
});

Is there a more standard way than the above?

Upvotes: 0

Views: 779

Answers (2)

danneu
danneu

Reputation: 9454

To mildly improve upon @James Moore's answer, you can also use this.assert(expression, [status], [message]) to short-circuit a route early if expression is not truthy.

I've converted their code to demonstrate:

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

Upvotes: 1

James Moore
James Moore

Reputation: 1901

Don't yield a simple object. Only yield an object when one or more of its properties is being assigned via a yieldable (promise, thunk, generator...).

Consider returning the updated item to prevent the need for additional api calls.

this.throw() is what I use.

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

Upvotes: 1

Related Questions