VersifiXion
VersifiXion

Reputation: 2292

Make a NestJS route send in response a pretty formatted JSON

I have a NestJS route which sends back in response, a JSON not well formatted (like minified), I want to make this JSON easier to read, like a JSON prettier or JSON formatted, Do someone knows how to do it in NestJS ? I accept answers for other NodeJS frameworks like Express, maybe it will work in NestJS too...

Upvotes: 3

Views: 5534

Answers (5)

Pepijn Olivier
Pepijn Olivier

Reputation: 977

  • Define return type string on your controller
  • Set the Content-Type: application/json response header
  • Use JSON.stringify to format your object with whitespace

Example controller code:

import { Controller, Get, Header } from '@nestjs/common';

@Controller('diagnostics')
export class DiagnosticsController {
  @Get()
  @Header('Content-Type', 'application/json')
  findAll(): string {
    const statusCode = 200;
    const statusText = 'OK';

    const info = {
      self: 'NestJS Diagnostics Report',
      status: {
        statusCode,
        statusText,
      },
    };

    return JSON.stringify(info, null, 2);
  }
}

Upvotes: 2

Misael Abanto
Misael Abanto

Reputation: 364

It works for me:

// src/main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  if (process.env.NODE_ENV !== 'production') {
    app.getHttpAdapter().getInstance().set('json spaces', 2);
  }
  await app.listen(process.env.PORT);
}

Upvotes: 4

Meredian
Meredian

Reputation: 990

While you shouldn't do it in prod as mentioned above, there's number of cases where it makes a lot of sense (e.g. in dev env). You can achieve this in a bit hacky way:

  1. Access express instance inside nest through breaking abstraction. It's not exposed on INest interface, so you'll need to cast it to any type to bypass Typescript check
  2. Set undocumented express property "json spaces", which will set formatting for all JSON responses over the app
const app = await NestFactory.create(AppModule);
if (process.env.NODE_ENV === 'development') {
  (app as any).httpAdapter.instance.set('json spaces', 2);
}
await app.listen(3000);

Upvotes: 1

Divine Touch
Divine Touch

Reputation: 19

You should try https://www.postman.com or https://insomnia.rest/. It can save you a lot of time when it comes to testing an API.

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70211

Prettifying the JSON response should be the responsibility of the client, not the server. Otherwise you could be sending a lot of white space which will bloat the response size and could lead to a crash due to having a response too large. If you are using something like Postman, it should be easy to prettify it, I think Postman might do it by default. If you are looking at the response in some web browser, you could use JSON.parse() on the response and it should make the response an actual JSON which console.log() would then print in a pretty way.

Upvotes: 3

Related Questions