0

I have a pretty simple question with respect to setting status codes after a database write. Let's say you're saving a new document to an object collection with something like mongoose. The following is inside a POST handler to some route, after some validation logic:

MyModel.create({
    prop: dataFromPost
}).then(
    () => {console.log("Success");},        // status => 201
    err => {console.log(`Error: ${err}`);}  // status => 5xx ???
);

response.writeHead(202);

Is this the proper approach? It just seems as tho if for some reason the write failed, then responding with 201 synchronously would be obviously the wrong thing to do.

Any advice with respect to handling this type of asynchronous branching in response flows would be greatly appreciated.

MFave
  • 1,044
  • 2
  • 8
  • 19

1 Answers1

1

You need to have your responses within the callback of any async requests. For example:

MyModel.create({
    prop: dataFromPost
}).then(() => {
   response.writeHead(201);
}, err => {
   response.writeHead(500);
})
dzm
  • 22,844
  • 47
  • 146
  • 226
  • So in this context would not even bother with a 202? – MFave Nov 07 '17 at 02:21
  • Right, you only send a response when there's a response to send. But I don't know your exact use case. Typically myself, I use code `200` when I'm sending a successful response. You'll actually need to send `response.end()` as well. Are you using just native node http server? – dzm Nov 07 '17 at 02:30
  • No, its koa. I think that's actually the reason why this isn't working for me, because I've tried putting the status code assignment in the callback and it doesn't register. What's going on exactly is abstracted away from me and I can't reason about it... Reading koa documentation now... – MFave Nov 07 '17 at 02:41
  • Do you have more code? I don't see any Koa code here. Can you include your full route code, if you're using kao-routes. – dzm Nov 07 '17 at 02:45
  • I solved the problem. But the answer kind of makes me not want to use koa anymore, lol. – MFave Nov 07 '17 at 03:27
  • @MFave Great. Yeah.. could check out http://expressjs.com/ if you're not committed to koa. – dzm Nov 07 '17 at 03:29