@2amtech/crudx

中文文档
1.0.4发布于 2025/01/08TypeScriptCommonJS构建来源已验证近 30 天下载 5183

NestJs CRUD for RESTful APIs - request query builder

原始使用文档
文档目录4 节
  1. Install
  2. Basics
  3. IntelliSense
  4. Further Reading

@2amtech/Crudx

The @2amtech/Crudx is a refactor inspired by the impressive work of nestjsx/crud, consolidating its three packages into one cohesive solution. It simplifies the creation of CRUD (Create, Read, Update, Delete) endpoints for RESTful applications with remarkable ease within Nest.js.

This tool provides decorators specifically designed for endpoint generation, global configurations, request validation, and specialized services, all tailored to enhance the efficiency and usability of Crudx across various contexts.

A comprehensive documentation offers a structured exploration of Crudx functionalities, meticulously divided into distinct sections. Each section is accompanied by illustrative samples and insightful comments, fostering a deeper understanding of how to effectively leverage Crudx in your projects.

Install

$ npm i @2amtech/crudx

Basics

Before diving into Crudx features, it's essential to define a basic Nest.js module for CRUD operations. Let's use the User module as a sample:

First, let's define an entity.

Crudx supports TypeORM for building entities, so let's implement it:

import { 
  AfterLoad,
  BaseEntity,
  Entity, 
  PrimaryGeneratedColumn, 
  Column,
  BeforeInsert,
  BeforeUpdate,
} from "typeorm";
import * as bcrypt from "bcryptjs";

@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn("uuid") 
  id: string;

  @Column({ unique: true, length: 125 })
  email: string;

  @Column({ type: "varchar", length: 80 })
  password: string; 

  private tempPassword?: string;

  @AfterLoad()
  private loadTempPassword(): void {
    this.tempPassword = this.password;
  }

  @BeforeInsert()
  private async hashPassword(): Promise<void> {
    this.password = await bcrypt.hash(this.password, 10);
  }

  @BeforeUpdate()
  private async encryptPassword(): Promise<void> {
    if (this.tempPassword !== null && this.tempPassword !== this.password) {
      try {
        await this.hashPassword();

        this.tempPassword = this.password;
      } catch (error) {
        if (error instanceof Error) {
          throw new Error("Unable to encrypt password: " + error.message);
        }
      }
    }
  }
}

Next, let's create a service:

import {Injectable} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { TypeOrmCrudService } from "@2amtech/crudx";
import { Catch, Injectable } from "@nestjs/common";
import { EntityNotFoundError, QueryFailedError } from "typeorm";

@Injectable()
@Catch(QueryFailedError, EntityNotFoundError)
export class UserService extends TypeOrmCrudService<User> {
  constructor(@InjectRepository(User) readonly repo) {
    super(repo);
  }
}

With the service in place, let's define our controller:

Note that we're utilizing the @Crud decorator. When it’s defined for a controller, it automatically creates the basic CRUD routes:

  • get /user
  • get /user/:id
  • post /user
  • post /user/bulk
  • patch /user/:id
  • put /user/:id
  • delete /user/:id

For further details, you can refer to the Controllers section.

In our sample, we're specifying some options for our @CRUD decorator: model and params.

The model option is the only required one for the @Crud() decorator. Its type property defines a class as the request body type, enabling data validation. Though not covered in our basics, you can find all related information in the request validation section. The provided type should be an Entity, Model or DTO.

By default, the generated routes will have a parameter named :id. This parameter is intended to represent the model's primary key. We're using the params options to instruct Crudx to define our param :id as a uuid type, indicating that it should match the id field of the User entity.

import { Crud, CrudController } from "@2amtech/crudx";
import { Controller } from "@nestjs/common";
import { User } from "./user.entity";
import { UserService } from "./user.service";

@Crud({
  model: {
    type: User,
  },
  params: {
    id: {
        field: "id",
        type: "uuid",
        primary: true,
    }
  }
})
@Controller("users")
export class UserController implements CrudController<User> {
  constructor(public service: UserService) {}
}

With the entity, service, and controller defined, all that's left is to export a module and import it into the application's main module:

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";

import { UserController } from "./user.controller";
import { User } from "./user.entity";
import { UserService } from "./user.service";

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}

IntelliSense

Due to the CRUD controllers being composed by the logic of the @Crud decorator, IntelliSense will not be available on composed methods. To enable your code to properly access the controller's methods from the this keyword, you can add these lines to your class:

import { Crud, CrudController } from '@2amtech/crudx';
import { User } from './user.entity.ts';

@Crud(User)
@Controller('user')
export class UserController implements CrudController<User> {
  constructor(public service: UserService) {}

  get base(): CrudController<User> {
    return this;
  }
}

While the examples provided above offer a simplistic demonstration, they effectively highlight the fundamental principles of utilizing Crudx. For more in-depth insights and comprehensive guidance, we encourage you to explore the dedicated sections outlined below, which deal with specific functionalities and advanced usage scenarios.

Further Reading

Thank you for exploring our resources. Happy coding!


web development has never been so fun
www.2am.tech

版本与发布记录

@2amtech/crudx 共发布 4 个版本,首次发布于 2024/08/05;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.0.4latest2025/01/081.8 年前
1.0.32025/01/081.8 年前
1.0.12024/08/222 年前
1.0.02024/08/052 年前

关于 @2amtech/crudx 的常见问题

@2amtech/crudx 是什么?

NestJs CRUD for RESTful APIs - request query builder

如何安装 @2amtech/crudx?

在项目目录运行 npm install @2amtech/crudx,或使用 pnpm add / yarn add / bun add。

@2amtech/crudx 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@2amtech/crudx 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@2amtech/crudx 可以商用吗?

@2amtech/crudx 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@2amtech/crudx 的下载量有多少?

根据 npm 官方下载统计,@2amtech/crudx 在 2026/10/05 – 2026/11/03 这 30 天内被下载 5,183 次,日均约 173 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@2amtech/crudx 还在维护吗?

最新版本 1.0.4 发布于 2025/01/08(1.8 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/08/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。