-1

I am new to Nest JS Framework and I dont whether I can use json-server to mock external API.

I have already checked NestJS documentation but its not having any example.

I found one question on Stack-overflow but it not complete Example Json-server mocking API instead of calls

I simply want to make one POST call and 1 GET Call.

Dont know which file I write these mocked POST and GET calls.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Akki
  • 1,718
  • 2
  • 29
  • 53

1 Answers1

4

My first question is, what is your purpose for using NestJS?

You can think of NestJS and json-server as "similar" in their goal; you would use one OR the other. Not both.

  • If your goal is just to mock data and server, then you have everything you need with json-server. You wouldn't need NestJS.
  • If what you are looking for is to mock data to retrieve instead of creating a database, you can simply create a simple object in NestJS and retrieve data from there.

For the latter, it might look something like this (not tested):

// app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from '../services/app.service';

@Controller('api')
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('/users')
  findAllUsers(): Promise<any> {
    return this.appService.findAllUsers();
  }
}


// app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {

  private getMockData() {
    return {
      users: [
        {
          name: 'john',
          email: 'john@doe.com',
        },
        {
          name: 'jane',
          email: 'jane@doe.com',
        },
      ],
    };
  }

  findAllUsers(): Promise<any> {
    return new Promise(function (resolve, reject) {
      const data = this.getMockData();
      if (data.users.length > 0) resolve(data.users);
      else reject('No users found');
    });
  }
}

Now you would just have to do the request GET <host>/api/users where the host will be something like http://localhost:8080 in your local machine.

E_net4
  • 27,810
  • 13
  • 101
  • 139