[Nestia] SDK and Mockup Simulator generation from Swagger Documents (Swagger to NestJS)
Tags: nestjs, opensource, typescript, programming
Published: 2023-07-08 18:46:35

## Preface
Introducing [nestia](https://github.com/samchon/nestia) in here `dev.to` community, I got many email requests that hoping another type of SDK Library generator for other backend languages and frameworks. 

Receiving their emails, I'd though that instead of making a duplicated libraries for other backend languages and frameworks, it would much better to support other environments in current [nestia](https://github.com/samchon/nestia) side. I thought that it would be a much easier and faster way to fulfill your requests.

So now, I introduce my new library `@nestia/migrate`, which can make SDK Library even in other backend languages and frameworks.




## Outline
```bash
# SETUP GLOBALLY
npm install -g @nestia/migrate

# DO MIGRATE
npx @nestia/migrate swagger.json output_directory
```

Migration tool from Swagger Documents to NestJS.

  - Github Repository: https://github.com/samchon/nestia
  - Related Document: https://nestia.io/docs/migrate

When you run `npx @nestia/migrate swagger.json <output>` command, `@nestia/migrate` will analyze your `swagger.json` file, and generate a NestJS project into the `<output>` direcory. If you're considering migration of your backend project to NestJS, `@nestia/migrate` will be a good starting point.

Also, `@nestia/sdk` can generate below things from NestJS project. 

  - [SDK (Software Development Kit)](https://nestia.io/docs/sdk/sdk)
  - [Mockup Simulator](https://nestia.io/docs/sdk/simulator)
  - [Automated e2e test functions](https://nestia.io/docs/sdk/e2e)

It means that, with `@nestia/migrate`, you can generate [SDK Library](https://nestia.io/docs/sdk/sdk) or [Mockup Simulator](https://nestia.io/docs/sdk/simulator) from every backend projects. If you don't have plan to migrate to NestJS, but hope to take advantages of it, `@nestia/migrate` will be a good choice. Languages and frameworks, they're no longer matter in backend development. 

Let's enjoy the new world with `@nestia/migrate`.




## SDK Library
Collection of DTO types and fetch functions.

  - Related Document: https://nestia.io/docs/sdk/sdk

If you're not aware with [`nestia`](https://github.com/samchon/nestia), the term SDK (Software Development Kit) library may sound unfamiliar. The SDK libray of NestJS means a collection of `DTO` types and `fetch` functions with type definitions for convenience. When you run `@nestia/sdk`, it will analyze your backend server codes, and generate such SDK library.

If my explanation is still not clear, let me show you an example. Look at below gif image, then you may understand what SDK library is. The left side is a NestJS server code, and the right side is a client (frontend) program code utilizing the SDK library. As you can see, client (frontend) developer can easily interact with your backend server just by taking advantages of type hints and auto completions of TypeScript.

Isn't it seem like convenient and safe? This is the SDK library what I mean.

![SDK](https://user-images.githubusercontent.com/13158709/215004990-368c589d-7101-404e-b81b-fbc936382f05.gif)

### NestJS Server Code
```typescript
import { Controller } from "@nestjs/common";
import typia from "typia";

import core from "@nestia/core";

import { IBbsArticle } from "@api/lib/structures/IBbsArticle";

@Controller("body")
export class TypedBodyController {
    @core.TypedRoute.Post()
    public async store(
        @core.TypedBody() input: IBbsArticle.IStore,
    ): Promise<IBbsArticle> {
        const output: IBbsArticle = {
            ...typia.random<IBbsArticle>(),
            ...input,
        };
        return output;
    }
}
```

### SDK Library Code
```typescript
/**
 * @packageDocumentation
 * @module api.functional.body
 * @nestia Generated by Nestia - https://github.com/samchon/nestia 
 */
//================================================================
import { Fetcher } from "@nestia/fetcher";
import type { IConnection, Primitive } from "@nestia/fetcher";

import type { IBbsArticle } from "./../../structures/IBbsArticle";

/**
 * @controller TypedBodyController.store()
 * @path POST /body
 * @nestia Generated by Nestia - https://github.com/samchon/nestia
 */
export async function store(
    connection: IConnection,
    input: store.Input,
): Promise<store.Output> {
    return Fetcher.fetch(
        connection,
        store.ENCRYPTED,
        store.METHOD,
        store.path(),
        input,
    );
}
export namespace store {
    export type Input = Primitive<IBbsArticle.IStore>;
    export type Output = Primitive<IBbsArticle>;

    export const METHOD = "POST" as const;
    export const PATH: string = "/body";
    export const ENCRYPTED: Fetcher.IEncrypted = {
        request: false,
        response: false,
    };

    export const path = (): string => {
        return `/body`;
    }
}
```



## Mockup Simulator
Embedded backend server simulator in SDK library.

  - Similar with [msw](https://mswjs.io/), but fully automated.
  - Related Document: https://nestia.io/docs/sdk/simulator

Like above SDK (Software Development Kit) library case, the word "Mockup Simulator" may sound unfamiliar, if you are not aware of [nestia](https://github.com/samchon/nestia). The "Mockup Simulator" means an embedded backend server simulator in SDK library generated by `@nestia/sdk`.

If you've experienced frontend development, you may know [msw - (Mockup Service Worker)](https://mswjs.io/). Mockup Simulator of [nestia](https://github.com/samchon/nestia) is almost same with it, but of [nestia](https://github.com/samchon/nestia) is fully automated. Besides, [msw](https://mswjs.io/) needs to write API interfaces and mockup codes by manually.

If you see actual Mockup Simulator code, then you may exactly understand what it is. Yes, the Mockup Simulator, it's just an internal function returning random data with same type of API interface. For reference, mockup data generation is being done by [`typia.random<T>()`](https://github.com/samchon/typia) function, which can analyze TypeScript type and generate optimal random generation code in the compliation level.

  - https://github.com/samchon/typia
  - 20,000x faster validation
  - 200x faster JSON serialization
  - With [nestia](https://github.com/samchon/nestia), boosts NestJS server performance 30x up

```typescript
/**
 * @packageDocumentation
 * @module api.functional.body
 * @nestia Generated by Nestia - https://github.com/samchon/nestia 
 */
//================================================================
import { Fetcher } from "@nestia/fetcher";
import type { IConnection } from "@nestia/fetcher";
import typia from "typia";

import { NestiaSimulator } from "./../../utils/NestiaSimulator";
import type { IBbsArticle } from "./../../structures/IBbsArticle";

/**
 * @controller BodyController.post()
 * @path POST /body
 * @nestia Generated by Nestia - https://github.com/samchon/nestia
 */
export async function post(
    connection: IConnection,
    body: IBbsArticle.IStore,
): Promise<post.Output> {
    return !!connection.simulate
        ? post.simulate(
              connection,
              body,
          )
        : Fetcher.fetch(
              connection,
              post.ENCRYPTED,
              post.METHOD,
              post.path(),
              body,
          );
}
export namespace post {
    export type Input = IBbsArticle.IStore;
    export type Output = IBbsArticle;

    export const METHOD = "POST" as const;
    export const PATH: string = "/body";
    export const ENCRYPTED: Fetcher.IEncrypted = {
        request: false,
        response: false,
    };

    export const path = (): string => {
        return `/body`;
    }
    export const random = (g?: Partial<typia.IRandomGenerator>): Output =>
        typia.random<Output>(g);
    export const simulate = async (
        connection: IConnection,
        body: post.Input,
    ): Promise<Output> => {
        const assert = NestiaSimulator.assert({
            method: METHOD,
            host: connection.host,
            path: path()
        });
        assert.body(() => typia.assert(body));
        return random(
            typeof connection.simulate === 'object' &&
                connection.simulate !== null
                ? connection.simulate
                : undefined
        );
    }
}
```




## Nestia Editor
New library `@nestia/editor` is coming.

If you're considering migration from your backend server to NestJS, I think current `@nestia/migrate` module is fully enough. 

However, if you don't want to migrate to NestJS, and just hope only SDK Library and Mockup Simulator, then current `@nestia/migrate` can be a little bit inconvenient for you. Installing and running `npx @nestia/migrate swagger.json output_directory` seems a little bit annoying, isn't it?

Therefore, I'm planning to make a new library `@nestia/editor`. It's a type of evolved `swagger-ui` embedding TypeScript Editor, `@nestia/migrate` and `@nestia/sdk`.

By embedding TypeScript Editor in `swagger-ui`, you can take advatanges of TypeScript compiler like type hints and auto-completions. Also, if you turn on simulation mode, `@nestia/editor` will utilize embeded Mockup Simulator of `@nestia/sdk`, instead of sending request to the real backend server.

Of course, as `@nestia/editor` includes `@nestia/migrate`, you can build and download SDK library and Mockup Simulator in the website. 

Look forward to it, I'll show you a new world.