Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'require' to import a JSON in NestJS controller?

I'm trying to return a json file as a controller response, but I can't get the content of the json.

import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';
import { Response } from 'express';

import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file is imported fine
const MOCKED_RESPONSE = require('./data/payment-method-mock'); // this json file is not found

@Controller('commons')
export class CommonController {

@Get('/payment-method')
  getPaymentMoethod(@Res() res: Response): any {
    res.status(HttpStatus.OK).send(MOCKED_RESPONSE);
  }

}

Actually the log returns: Error: Cannot find module './data/payment-method' and the app doesn't compile

I have done this with express (even with typescript) and works fine.

I don't know if i have to setup my project to read jsons (I'm newby on nest). By the moment I have created a typescript file exporting a const with the json content and I called it successfuly

like image 228
Daniel Delgado Avatar asked Dec 18 '19 00:12

Daniel Delgado


1 Answers

  1. I guess the problem lies in the way you import your .json file (change import instead of const)
  2. Another advice or solution would be to leverage the .json() method of the res object (which is actually the express adapter response object).

Let's try with this code:

Your common.controller.ts file:

import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';
import { Response } from 'express';

import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file should still be imported fine
import * as MOCKED_RESPONSE from './data/payment-method-mock.json'; // or use const inside the controller function

@Controller('commons')
export class CommonController {

@Get('/payment-method')
  getPaymentMoethod(@Res() res: Response): any {
    res.status(HttpStatus.OK).json(MOCKED_RESPONSE); // <= this sends response data as json
  }
}

Also in your tsconfig.json file, don't forget to add this line:

tsconfig.json

{
  "compilerOptions": {
    // ... other options 

    "resolveJsonModule": true, // here is the important line, this will help VSCode to autocomplete and suggest quick-fixes

    // ... other options
}

Last thoughts: you could use the sendfile() method of the res object depending on whether you want to send back a json file or the content of your json file.

Let me know if it helps ;)

like image 68
A. Maitre Avatar answered Sep 28 '22 07:09

A. Maitre