Originally I had code that looked like:
app.get("/doc/:id", function (req, res) {
db.get(prefix(req.params.id)).pipe(res);
});
If db.get
returned a 404 / the document was not found, the response to GET /doc/id
would have a 404 and appropriate error automatically.
I need to do some transformation on the document if it is returned, like so:
db.get(prefix(req.params.id))
.pipe(JSONStream.parse())
.pipe(es.map(function (data, cb) {
cb(null, deprefix(data._id));
})
.pipe(res)
This works great if the document is found, but if it's not I run into various issues like data._id
not existsing. I can handle this manually by conditionally checking the data, but the response doesn't get the error headers such as a 404 status code automatically at this point -- I have to set it myself.
Is there any way to pipe header information while also doing a transform on the body of an HTTP response? Is there any concept of conditional piping?