Json-服务器模拟 API 而不是调用

Json-server mocking API instead of calls

我正在使用 NestJS (NodeJS) 制作一个 API,以便在本地环境中 运行 它而不需要所有外部 API 运行ning,我想在 API 运行ning.

时模拟对外部 API 的调用

为了做到这一点,我选择Json-server来做,代码如下:

mockserver.ts:

export async function bootstrap() {
  const app = create();
  app.use(
    defaults({
      logger: true,
      static: 'static',
    }),
    router(dbJSON),
    jsonServer.rewriter(routesJSON),
  );

  app.use('/api', router);
}

我也试过了:

export async function bootstrap() {
  const app = create();
  app.use(
    defaults({
      logger: true,
      static: 'static',
    }),
    router(db),
    jsonServer.rewriter(routesJSON),
  );

  app.use('/api', router);
  const port = process.env.mockPort ?? 8080;
  app.listen(port);

main.ts :

async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  const mocks = await import('../mocks/server');
  app.use(await mocks.bootstrap(null));

  await app.listen(DEFAULT_HTTP_PORT, DEFAULT_HOST);
}

但是,我的 API 本身被模拟了,而不是使用数据库和给定 Json-server 的路由模拟对外部 API 的调用。

关于如何在 运行ning 时模拟对外部 API 的 API 调用的任何想法?或者如何使 json-server mock call 只调用 httpService 而不是 API 本身

我以前没试过这个,但我认为你要么需要配置现有的 HttpModule 有时转发调用,要么用一个新模块包装 HttpModule 来决定是否将请求转发到真实服务器或模拟服务器.

您可以通过 register. See the async configuration if you want to inject ConfigService to configure it based off of an environment variable that determines if you're local or not. The config object is an Axios request configHttpModule 配置。但是,我没有看到通过配置重定向请求的方法。

HttpModule 使用 axios,所以另一个选项是 axios interceptors. In a request interceptor, you could have it only override config.url when running locally. To set up interceptors at the beginning of the app, you could create a module MyHttpModule that injects HttpService, and in an onModuleInit, get a reference to the axios instance and set the interceptors. Check out this example 我找到了。