servie icon indicating copy to clipboard operation
servie copied to clipboard

Dealing with a application/json Request chain

Open zomble opened this issue 9 years ago • 4 comments

Hey Blake,

When throwing a Request object down a chain of handlers, I have one that spots that the content-type is application/json and the content is a string I attempt to decode it. If the content is an invalid JSON string it will halt the chain and return a 400 error.

However if it is valid, my default action was to set the body to the now decoded object, however it gets encoded again. I can understand the reasoning.

Can you share your thoughts on how I should be handling this situation when using servie?

zomble avatar Jan 23 '17 05:01 zomble

One thing you can do is to put it on a different property. If you're using a newer version of node.js, I'd definitely promote using symbols (e.g. const body = new Symbol('body')) in the middleware chain. I don't think this is the best solution though, I think over-reliance of the middleware stack is an anti-pattern. Is there a reason middleware is needed here?

Instead, you could define a function that enables this. E.g.

function parse (req: Request): Promise<{}> {
  // Do stuff like check for content encoding and content type before proceeding.
  return req.text().then(x => JSON.parse(x))
}

Then you can use that anywhere you need:

const body = await parse(req)

I'd be happy to define this middleware officially in the next day. I hadn't actually needed it yet since I'm currently using this as a compat layer in AWS Lambda, but designed it with API clients (like https://github.com/blakeembrey/popsicle) and servers in mind.

blakeembrey avatar Jan 23 '17 06:01 blakeembrey

I'm not actually using middleware. I just thought it was an easy enough scenario to put my question into.

It's interesting to me as most request contexts I've used before either do this magic for me, or allow me to modify the body as I see fit. And then later do more magic to it to prepare it for the wire.

I don't see a design issue with what you have done. I can see it's merit in representing a Request as a it actually is, and not allowing it to be in a state that is not accurate and would need fixing at a later time.

I can work with it by switching around my logic, to JSON.parse where needed and make sure errors/exceptions sourced from it correctly translate into responses somewhere else.

zomble avatar Jan 23 '17 06:01 zomble

It's interesting to me as most request contexts I've used before either do this magic for me, or allow me to modify the body as I see fit. And then later do more magic to it to prepare it for the wire.

In some cases, definitely. For instance, Koa has two branches of logic that stringifies JSON before sending it but keeps it as JSON before that, therefore having to change the length right before sending it. Unfortunately, that's a bit messy when working with different transports that might implement things differently.

I can work with it by switching around my logic, to JSON.parse where needed and make sure errors/exceptions sourced from it correctly translate into responses somewhere else.

Yes, the function itself should throw and the transport itself can catch and translate it to a HTTP response (similar to finalhandler - https://github.com/pillarjs/finalhandler). That way, if you want to inject your own error handler it looks very much like Koa:

import { compose } from 'throwback'

compose([
  async function (req, res, next) {
    try {
      return next()
    } catch (err) {
      res.status = err.status || 500
      res.body = 'Something here, stack in development, etc'
    }
  },
  async function (req, res, next) {
    throw req.error('Bad request', 'EBAD', 400)
  }
])

blakeembrey avatar Jan 23 '17 07:01 blakeembrey

I just wrote a generic body parser that can be used with servie here: https://github.com/blakeembrey/node-get-body. You can just parse and use it within the handler. If you do need to pass it onward via middleware, perhaps using a little wrapper and assigning it to the req object would work or passing it as another argument.

blakeembrey avatar Jan 24 '17 21:01 blakeembrey