发布于 2026-01-05 2 阅读
0

[Nestia] 大幅提升 NestJS 服务器速度,操作更简便(最高提升 20,000 倍,并支持 tRPC)

[Nestia] 大幅提升 NestJS 服务器速度,操作更简便(最高提升 20,000 倍,并支持 tRPC)

前言

Nestia 标志

正如我在之前的Typia 系列文章 (dev.to)中承诺的那样,我将向大家介绍我的新库nestia,它可以使编程NestJS更快、更轻松。

借助我的新库Nestia,您只需为每个 API 函数编写一行代码,即可显著提升NestJS服务器性能。此外,您还可以构建 SDK 库,从而为其他客户端开发人员提供极大的便利。

让我们看看NestiaNestJS ,想象一下你的服务器会变得多么强大。

SDK 示例

左边是NestJS服务器端代码,右边是使用 SDK 的客户端代码。

您可以更轻松、更安全地编写客户端代码。


纯 TypeScript 类型

在[此处应填写具体术语,例如: ]中NestJS,您需要利用这些库来定义DTO:

  • class-validator
  • class-transformer
  • @nestjs/swagger

我讨厌这些库,因为它们迫使开发者定义重复的类型,就像下面这样。只要你按照官方指南使用它们NestJS,就永远无法避免在 TypeScript 类型定义和装饰器中出现重复的类型定义。

让我们看看这些库是如何让 DTO 变得丑陋的:



export class BbsArticle {
    @IsString()
    @ApiProperty({
        format: "uuid",
    })
    id!: string;

    // DUPLICATED SCHEMA DEFINITION
    // - duplicated function call + property type
    // - have to specify `isArray` and `nullable` props by yourself
    @IsArray()
    @IsObject()
    @ValidateNested()
    @Type(() => AttachmentFile)
    @ApiProperty({
        type: () => AttachmentFile,
        nullable: true,
        isArray: true,
        description: "List of attached files.",
    })
    files!: AttachmentFile[] | null;

    @IsString()
    @IsOptional()
    @ApiProperty({
        type: "string",
        nullable: true,
        minLength: 5,
        maxLength: 100,
        description: "Title of the article.",
    })
    title!: string | null;

    @IsString()
    @ApiProperty({
        description: "Main content body of the article."
    })
    body!: string;

    @IsString()
    @ApiProperty({
        format: "date-time",
        description: "Creation time of article",
    })
    created_at!: string;
}

export class AttachmentFile {
    @IsString()
    @IsOptional()
    @ApiProperty({
        type: "string",
        nullable: true,
        maxLength: 255,
        pattern: "^[a-zA-Z0-9-_]+$",
        description: "File name.",
    })
    name!: string | null;

    @IsString()
    @IsOptional()
    @ApiProperty({
        type: "string",
        nullable: true,
        maxLength: 255,
        pattern: "^[a-zA-Z0-9-_]+$",
        description: "File extension.",
    })
    extension!: string | null;

    @IsString()
    @ApiProperty({
        format: "url",
        description: "URL of the file.",
    })
    url!: string;
}


Enter fullscreen mode Exit fullscreen mode

相反,使用Nestia,您可以仅使用纯 TypeScript 类型定义 DTO。因此,您无需担心类型定义重复的问题。此外,它甚至支持Nestia接口类型的 DTO。

让我们看看Nestia如何让 DTO 变得更轻松、更美观:



export interface IBbsArticle {
    /**
     * Primary Key.
     * 
     * @format uuid
     */
    id: string;

    /**
     * List of attached files.
     */
    files: IAttachmentFile[] | null;

    /**
     * Title of the article.
     * 
     * @minLength 5
     * @maxLength 100
     */
    title: string | null;

    /**
     * Main content body of the article.
     */
    body: string;

    /**
     * Creation time of article.
     * 
     * @format date-time
     */
    created_at: string;
}

export interface IAttachmentFile {
    /**
     * File name.
     * 
     * @pattern ^[a-z0-9]+$
     * @maxLength 255
     */
    name: string | null;

    /**
     * File extension.
     * 
     * @pattern ^[a-z0-9]+$
     * @maxLength 8
     */
    extension: string | null;

    /**
     * URL of the file.
     * 
     * @format uri
     */
    url: string;
}


Enter fullscreen mode Exit fullscreen mode

超快速验证

如果您看过我之前的Typia 系列文章 (dev.to),阅读上面的#Pure TypeScript 类型部分,您可能会怀疑nestia正在使用typia

是的,Nestia使用了Typia ,这也是Nestia能够使用纯 TypeScript 类型作为 DTO 的秘诀所在。此外,由于Nestia使用了Typia,它还能提供超快的验证速度。

你还记得吗?Typiaclass-validator的验证速度比你现在使用的速度快 20,000 倍。只需使用NestiaNestJS ,你也能在服务器上实现如此超快的验证速度NestJS

现在,将你的class-validatorDTO 类更改为纯 TypeScript 类型,并使用@TypedBody()类似下面的函数。这样,​​你的NestJS服务器验证速度(针对请求体数据)将提升 20,000 倍。

看起来非常简单又美好,不是吗?



import { TypedBody, TypedRoute } from "@nestia/core";
import { Controller } from "@nestjs/common";

import { IBbsArticle } from "./IBbsArticle";

@Controller("bbs/articles")
export class BbsArticlesController {
    @TypedRoute.Post()
    public async store(
        // 20,000x faster validation
        @TypedBody() input: IBbsArticle.IStore
    ): Promise<IBbsArticle> {
        return {
            ...input,
            id: "2b5e21d8-0e44-4482-bd3e-4540dee7f3d6",
            created_at: "2023-04-23T12:04:54.168Z",
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

断言函数基准测试

使用Intel i5-1135g7 处理器和 Surface Pro 8进行测试


超快速序列化

Nestia使用的是Typia。因此,出于与#Superfast Validation相同的原因,JSON 序列化速度也可以比class-transformer目前NestJS使用的速度快 200 倍。

@TypedRoute.${method}()只需在 API 函数上使用装饰器,NestJS服务器的 JSON 序列化速度(针对响应体数据)就能提升 200 倍。

如果您想了解服务器端的 JSON 序列化速度,请查看下面的服务器基准测试图表。只需采用Nestia并利用其@TypedRoute.${method}()功能,您的NestJS服务器最多可以处理 30 倍以上的请求。

NodeJS 服务器中的大多数操作都在后台线程中异步执行,这被称为“基于事件的非阻塞 I/O 模型”。然而,JSON 序列化是一个在主线程上运行的同步操作。因此,如果 JSON 序列化速度慢,就会导致整个服务器程序运行缓慢。

它看起来很强大,不是吗?



import { TypedRoute } from "@nestia/core";
import { Controller } from "@nestjs/common";

import { IBbsArticle } from "./IBbsArticle";

@Controller("bbs/articles")
export class BbsArticlesController {
    // 200x faster JSON serialization
    @TypedRoute.Get("random")
    public async random(): Promise<IBbsArticle> {
        return {
            id: "2b5e21d8-0e44-4482-bd3e-4540dee7f3d6",
            title: "Hello nestia users",
            body: "Just use `TypedRoute.Get()` function like this",
            created_at: "2023-04-23T12:04:54.168Z",
            files: [],
        };
    }
}


Enter fullscreen mode Exit fullscreen mode

字符串化函数基准测试

使用Intel i5-1135g7 处理器和 Surface Pro 8进行测试

服务器基准测试

使用Intel i5-1135g7 处理器和 Surface Pro 8进行测试


SDK生成

您了解tRPC吗?如果您使用 tRPC 开发 NodeJS 后端服务器,则无需向其他客户端开发人员提供任何 Swagger 文档。您只需向他们发送一个交互库即可。

顺便一提,tRPC适合构建玩具项目,但不适合开发企业级后端服务器。因此,许多NestJS爱好者曾请求tRPC团队提供支持NestJS。但考虑到tRPC的原理,它永远无法支持NestJS

我提供的是NestiaNestJS,它支持 SDK 生成。只需运行命令,Nestia就会分析您的后端服务器代码,并在编译级别生成最佳的 SDK 库。npx nestia sdkNestJS

看看下面的 GIF 图片,想象一下 SDK 将如何帮助你的其他客户端开发人员。他们只需导入 SDK 库,即可使用自动补全功能调用 API 函数。

如果他们犯了任何错误,编译器都会检测到,因此您不必因为这些错误而遭受运行时错误的影响。

SDK 示例

左边是NestJS服务器端代码,右边是使用 SDK 的客户端代码。

您可以更轻松、更安全地编写客户端代码。

文章来源:https://dev.to/samchon/nestia-boost-up-your-nestjs-server-much-faster-and-easier-maximum-20000x-faster-59o5