Outline

nestia.config.ts
import { INestiaConfig } from "@nestia/sdk";
import { NestFactory } from "@nestjs/core";
// import { FastifyAdapter } from "@nestjs/platform-fastify";
 
import { YourModule } from "./src/YourModule";
 
const NESTIA_CONFIG: INestiaConfig = {
  input: async () => {
    const app = await NestFactory.create(YourModule);
    // const app = await NestFactory.create(YourModule, new FastifyAdapter());
    // app.setGlobalPrefix("api");
    // app.enableVersioning({
      //     type: VersioningType.URI,
    //     prefix: "v",
    // })
    return app;
  },
  output: "src/api",
  simulate: true, // supports simulation mode
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;

Nestia SDK library supports Mockup simulator.

When generating SDK library, if you configure simulate property of nestia.config.file to be true, newly generated SDK library will support mockup simulation mode for frontend developers. With the mockup simulator, frontend developers can simulate NestJS backend server with internal mock functions, instead of connecting to the real backend server.

Therefore, with the mockup simulator, frontend development can be started even when the backend server is not ready yet. Mockup simulator of Nestia SDK will replace the real backend server, validating request data, and returning mockup data as response.

Within framework of backend developers, they also do not need to be suffered from the mock-up data composition. Also, as nestia can automatically generate e2e test functions, backend developers can concentrated only on the business logic.

Confguration

nestia.config.ts
import { INestiaConfig } from "@nestia/sdk";
import { NestFactory } from "@nestjs/core";
// import { FastifyAdapter } from "@nestjs/platform-fastify";
 
import { YourModule } from "./src/YourModule";
 
const NESTIA_CONFIG: INestiaConfig = {
  input: async () => {
    const app = await NestFactory.create(YourModule);
    // const app = await NestFactory.create(YourModule, new FastifyAdapter());
    // app.setGlobalPrefix("api");
    // app.enableVersioning({
    //     type: VersioningType.URI,
    //     prefix: "v",
    // })
    return app;
  },
  output: "src/api",
  simulate: true, // supports simulation mode
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;

Make nestia.config.ts file and run npx nestia sdk command.

At first, create nestia.config.ts file through npx nestia init command. It would be placed on the top level directory of your NestJS backend project. For reference, tsconfig.json file also must be placed in the top level directory, too. After creation, configure the nestia.config.ts file referencing above example code and type definition.

At least, you’ve to configure those three properties. Also, if you’ve decided to support mockup simulator for frontend developers, I recommend you to configure two properties more, for automatic e2e functions generation and SDK library distribution.

  • Essential
    • input: Accessor of controller classes
    • output: Path of output directory for SDK library
    • simulate: Whether to support simulator or not
  • Recommended
    • e2e: Path of output directory for E2E test functions
    • distribute: Target directory for SDK library distribution

When you’ve completed above configuration, just run npx nestia sdk command. Then, SDK library would be generated into the $config.output directory, with simulation mode supporting. If you want to generate e2e functions automatically, run npx nestia e2e command after.

By the way, nestia.config.ts supports alternative options specifying the target controller classes instead of using the Module instance. If your backend application server does not have special configuration like setGlobalPrefix, enableVersioning and RouterModule, it is okay to specifying the target controller classes just by writing their file path like below.

nestia.config.ts
import { INestiaConfig } from "@nestia/sdk";
 
const NESTIA_CONFIG: INestiaConfig = {
  input: "src/**/*.controller.ts",
  output: "src/api",
  simulate: true,
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;

Code Analysis

src/api/functional/bbs/articles/index.ts
/**
 * Update an article.
 *
 * @param section Section code
 * @param id Target article ID
 * @param input Content to update
 * @returns Updated content
 *
 * @controller BbsArticlesController.update()
 * @path PUT /bbs/:section/articles/:id
 * @nestia Generated by Nestia - https://github.com/samchon/nestia
 */
export async function update(
  connection: IConnection,
  section: string,
  id: string & Format<"uuid">,
  input: update.Input,
): Promise<update.Output> {
  return !!connection.simulate
    ? update.simulate(connection, section, id, input)
    : PlainFetcher.fetch(
        {
          ...connection,
          headers: {
            ...connection.headers,
            "Content-Type": "application/json",
          },
        },
        {
          ...update.METADATA,
          path: update.path(section, id),
        } as const,
        input,
      );
}
export namespace update {
  export type Input = Primitive<IBbsArticle.IStore>;
  export type Output = Primitive<IBbsArticle>;
 
  export const METADATA = {
    method: "PUT",
    path: "/bbs/articles/:section/:id",
    request: {
      type: "application/json",
      encrypted: false,
    },
    response: {
      type: "application/json",
      encrypted: false,
    },
    status: null,
  } as const;
 
  export const path = (
    section: string,
    id: string & Format<"uuid">,
  ): string => {
    return `/bbs/${encodeURIComponent(
      section ?? "null",
    )}/articles/${encodeURIComponent(id ?? "null")}`;
  };
 
  export const random = (g?: Partial<typia.IRandomGenerator>): Output =>
    typia.random<Output>(g);
 
  export const simulate = async (
    connection: IConnection,
    section: string,
    id: string & Format<"uuid">,
    input: update.Input,
  ): Promise<Output> => {
    const assert = NestiaSimulator.assert({
      method: METHOD,
      host: connection.host,
      path: path(section, id),
    });
    assert.param("section")(() => typia.assert(section));
    assert.param("id")(() => typia.assert(id));
    assert.body(() => typia.assert(input));
    return random(
      typeof connection.simulate === "object" && connection.simulate !== null
        ? connection.simulate
        : undefined,
    );
  };
}

Let’s read generated SDK library code, and understand which features are supported

At first, you can find that mock-up data is composed by typia.random<T>() function. Also, simulator function validates path parameters and request body data through typia.assert<T>() function. If the validation fails, 400 status error would be thrown.

At last, if frontend developer turns off simulation mode by configuring IConnection.simulate value to be false, the SDK library stops NestJS backend server simulating, and just start communicating with the real backend server.