curveball / core

The Curveball framework is a TypeScript framework for node.js with support for modern HTTP features.
https://curveballjs.org/
MIT License
526 stars 7 forks source link

Pretty-print JSON output before output #169

Closed spidgorny closed 2 years ago

spidgorny commented 3 years ago

How can I make the JSON output to be pretty-printed (line breaks and indents)?

Function sendBody() in http-utils.ts does JSON.stringify(body). Any way to make it configurable?

I think I can set the res.body in ALL my controllers to pre-formatted JSON string, but this can be too much changes for a trivial problem.

Is there a output middleware? I've only seen middleware that processes input in some way.

evert commented 3 years ago

All middlewares can operate on both input and output.

Here's a simple way to do this:

app.use( async (ctx, next) => {
  await next();
  if (ctx.response.body && typeof ctx.response.body === 'object') {
    ctx.response.body = JSON.stringify(ctx.response.body, null, 2);
  }
});

Note that the 'object check' here is imperfect, because there's a few types that are objects, but get special treatment (like streams.Readable and Buffer). So if you use either of those, you probably don't want to stringify them.

I would also recommend you take a look at Curveball browser:

https://github.com/curveball/browser

This is a middleware that will render pretty HTML wrappers around your JSON if a developer directly opens up the API in a browser. If you haven't ever seen this, it might be worth a look as it can really give your API superpowers.