百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
N

NestJS-Crud-Automator

> 编程语言
开源

NestJS-Crud-Automator 一个用于在 NestJS 应用中自动执行 CRUD 操作的强大库 目录 - 描述 - 特性 - 使用 - 示例 - 文档 - 许可 - 发行历史 - 社区 - 文件 - 代码 - 发行人 - 订阅 - 订阅 RSS - 订阅 Atom - 订阅 GitHub - 订阅 Twitter - 订阅 Facebook - 订阅 LinkedIn - 订阅 Reddit - 订阅 YouTube - 订阅 Slack - 订阅 Discord - 订阅 Telegram - 订阅 GitHub - 订阅 Twitter - 订阅 Facebook - 订阅 LinkedIn - 订阅 Reddit - 订阅 YouTube - 订阅 Slack - 订阅 Discord - 订阅 Telegram - 订阅 GitHub - 订阅 Twitter - 订

379 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

NestJS-Crud-Automator 一个用于在 NestJS 应用中自动执行 CRUD 操作的强大库 目录 - 描述 - 特性 - 使用 - 示例 - 文档 - 许可 - 发行历史 - 社区 - 文件 - 代码 - 发行人 - 订阅 - 订阅 RSS - 订阅 Atom - 订阅 GitHub - 订阅 Twitter - 订阅 Facebook - 订阅 LinkedIn - 订阅 Reddit - 订阅 YouTube - 订阅 Slack - 订阅 Discord - 订阅 Telegram - 订阅 GitHub - 订阅 Twitter - 订阅 Facebook - 订阅 LinkedIn - 订阅 Reddit - 订阅 YouTube - 订阅 Slack - 订阅 Discord - 订阅 Telegram - 订阅 GitHub - 订阅 Twitter - 订

NestJS-Crud-Automator

A powerful library for automating CRUD operations in NestJS applications

Table of Contents

  • Description
  • Features
  • Installation
  • Usage
    • Basic Usage
    • Advanced Usage
  • Subscriber System (Hooks)
  • Swagger Documentation
  • Migrating to 4.0
  • Migrating to 3.0
  • Current Status
  • AI Agent Skill
  • FAQ
  • License

Description

NestJS-Crud-Automator is a comprehensive library designed to eliminate repetitive code when building RESTful APIs with NestJS. It provides a suite of decorators, utilities, and validation tools that automatically generate controllers, DTOs, and service methods for handling Create, Read, Update, and Delete operations. This library significantly reduces development time by providing a declarative approach to API development. By simply describing your entity properties once, the library auto-generates all the necessary boilerplate code including Swagger documentation, validation rules, and transformation logic. Perfect for developers working on data-heavy applications who want to focus on business logic rather than repetitive CRUD implementation.

The core philosophy of this library is built on four pillars: being Declarative (describe your API, don't code it), writing Minimum Code (drastically reduce boilerplate), ensuring Flexibility (override or extend any automated behavior), and guaranteeing Type-Safety (leverage TypeScript to prevent errors). It achieves this through real-time in-memory code generation, a heavy reliance on decorators for configuration, and smart conventions to reduce setup.

Features

  • ✨ ️ Automatic generation of controllers, DTOs, and service methods for CRUD operations
  • ✨ ** Comprehensive Swagger/OpenAPI documentation generation for all endpoints**
  • ✨ ✅ Built-in validation rules with class-validator integration
  • ✨ ** Data transformation with class-transformer for request/response handling**
  • ✨ ** Type-safe decorators for entity properties with rich metadata support**
  • ✨ ** Authentication and authorization guards integration**
  • ✨ ** Advanced filtering, sorting, and generated PAGE/CURSOR pagination for list operations**
  • ✨ ** Generated nested GET/GET_LIST reads with owner path scoping and stable server ordering**
  • ✨ ** Support for object relations with include-driven loading**
  • ✨ ⚡ Performance optimized with TypeORM integration for database operations
  • ✨ ** Full support for TypeScript with strong typing throughout the library**
  • ✨ Hooks and Subscriber System: Intercept and extend business logic at both the controller and service level.
  • ✨ Dynamic and Polymorphic DTOs: Generate DTOs on-the-fly based on discriminator fields.
  • ✨ Guard-Based Field Exposure: Generate route-specific response DTOs based on configured guard classes.
  • ✨ ** Declarative Authorization Policies:** Subscriber-style policies with automatic guard wiring, scopes, and response transforms.
  • ✨ Request Tracing: Built-in CorrelationIDResponseBodyInterceptor to correlate requests and logs.
  • ✨ Convention over Configuration: Smart defaults for service and DTO naming to reduce boilerplate.

Installation

Install NestJS-Crud-Automator using your preferred package manager:

bash
# Using npm
npm install @elsikora/nestjs-crud-automator

# Using yarn
yarn add @elsikora/nestjs-crud-automator

# Using pnpm
pnpm add @elsikora/nestjs-crud-automator

Version 3.0.2 is the published baseline before the current generated-route work. The source now includes an intentional breaking capability boundary for generated service calls and must be released as a new major; package versions remain owned by release automation. Pin the exact released version your application has verified and review Migrating to 4.0.

Prerequisites

Make sure you have the following dependencies installed in your NestJS project:

  • NestJS @nestjs/common and @nestjs/core >=11.1.24
  • @nestjs/passport >=11.0.5
  • @nestjs/platform-fastify >=11.1.24
  • @nestjs/swagger >=11.0.3
  • @nestjs/throttler >=6.5.0
  • TypeORM >=0.3.20
  • Fastify >=5.8.5
  • class-validator >=0.15.1
  • class-transformer >=0.5.1
  • lodash >=4.18.1

You might need to install these peer dependencies if they're not already in your project:

bash
npm install @nestjs/common @nestjs/core @nestjs/passport @nestjs/platform-fastify @nestjs/swagger @nestjs/throttler typeorm class-transformer class-validator fastify lodash

Usage

Basic Usage

1. Define Your Entity

First, define your entity with the ApiPropertyDescribe decorators to provide metadata for CRUD generation:

…

CREATED_AT, UPDATED_AT, and RECEIVED_AT identify server-owned infrastructure timestamps. Generated CREATE, UPDATE, and PARTIAL_UPDATE body DTOs omit them while response DTOs retain them. Exclusion follows the semantic identifier, not the property name; use DATE for a writable business date.

Set isAutoDtoEnabled: false on ApiPropertyDescribe when a described entity property must remain outside every Automator-generated BODY, PARAMETERS, QUERY, and RESPONSE DTO. The property keeps its metadata and TypeORM mapping and remains available to manual DTOs, but it is also omitted from generated Swagger relation components and generated filter/order input. Route- or DTO-level isEnabled: true cannot re-enable it. An explicit ApiPropertyCopy may deliberately copy it into a manual DTO while retaining the source metadata's other route, DTO, guard, and validation rules.

2. Create a Service

Create a service with the ApiService decorator to add CRUD operations:

…

3. Create a Controller

Create a controller with the ApiController decorator to generate all CRUD endpoints:

…

Use response.headers for Swagger/OpenAPI response header documentation only. Authentication securityRequirements map to OpenAPI route requirements: one object means all listed schemes are required together, while multiple objects are alternatives. The scheme names must match the names registered in your app-owned DocumentBuilder configuration.

Top-level authentication.bearerStrategies and authentication.securityStrategies are not supported; put scheme names inside authentication.securityRequirements.

Advanced Usage

Custom Validation

Add custom validators to your DTOs:

typescript
import { ApiController, EApiRouteType, EApiDtoType, AllOrNoneOfListedPropertiesValidator } from "@elsikora/nestjs-crud-automator";

@ApiController({
	entity: UserEntity,
	name: "Users",
	routes: {
		[EApiRouteType.CREATE]: {
			autoDto: {
				[EApiDtoType.BODY]: {
					validators: [
						{
							constraintClass: AllOrNoneOfListedPropertiesValidator,
							options: ["firstName", "lastName"],
						},
					],
				},
			},
		},
	},
})
export class UserController {
	constructor(public service: UserService) {}
}

Request Transformation

Automatically transform request data:

…

Handling Relations

Configure include-driven relation loading:

…

Request relation relations.request.load enables hydration, and relations.request.load.include selects the direct request body relations to hydrate. Omitted service mappings use ${relationName}Service; relations.request.load.services only overrides those controller property names. Nested request include objects are passed to the direct relation service as TypeORM relations; nested request references are not recursively hydrated. load.relationLoadStrategy can be used on request or response load configs to choose TypeORM "join" or "query" loading.

relations.request.load.locks applies native TypeORM pessimistic_read or pessimistic_write locks to configured direct relation service get() calls. Locks require an active Automator transaction and are acquired in load.include declaration order. Locked loads disable implicit TypeORM eager-relation joins. A locked direct relation with explicit nested includes must use relationLoadStrategy: "query" so the nested loads share the manager without inheriting the row lock. Service inputs remain entity-based: scalar relation references are an HTTP/controller hydration contract, not a widened service method contract.

Custom DTOs

Use custom DTOs instead of auto-generated ones:

…

For GET_LIST, response DTOs support two explicit modes:

  • [EApiDtoType.RESPONSE]: PublicUserListResponseDto when the app owns the whole list wrapper.
  • [EApiDtoType.RESPONSE]: { itemType: PublicUserResponseDto } when the framework owns the list wrapper and the app owns each item shape.

Use the item DTO mode when you only need to narrow each returned item:

typescript
import { Expose } from "class-transformer";
import { ApiController, EApiDtoType, EApiRouteType } from "@elsikora/nestjs-crud-automator";

class PublicUserResponseDto {
	@Expose()
	id!: string;

	@Expose()
	username!: string;
}

@ApiController({
	entity: UserEntity,
	routes: {
		[EApiRouteType.GET_LIST]: {
			dto: {
				[EApiDtoType.RESPONSE]: {
					itemType: PublicUserResponseDto,
					name: "PublicUserListResponseDto",
				},
			},
		},
	},
})
export class UserController {
	constructor(public service: UserService) {}
}

The shown route omits pagination config, so it uses PAGE and keeps count, currentPage, items, totalCount, and totalPages, while items are serialized with PublicUserResponseDto. A route that opts into CURSOR instead uses the flat { items, nextCursor, previousCursor } wrapper, provided its item DTO satisfies the CURSOR proof below.

For CURSOR, custom DTO metadata must keep every potential order field and final primary tie-breaker as a same-name, required, non-null, raw response scalar. A full custom wrapper must prove exactly items, nextCursor, and previousCursor. Wire-time aliases/transforms that change protected fields fail closed; PAGE custom DTO behavior is unchanged.

Authorization

Authorization now has two first-class modes:

  • hooks: auto-discovered @ApiAuthorizationPolicy({ entity }) classes
  • iam: attachment/document-based IAM evaluation with optional boundaries

@ApiControllerSecurable() is marker-only. It turns on the authorization pipeline, but mode selection and all authorization configuration live in @ApiController({ authorization: ... }). Each route uses exactly one mode, and route config can override the controller default with routes[routeType].security.authorization.mode.

Runtime authorization actions

@ApiMethod(...) uses one route action identity: metadata.resource.action. Generated CRUD routes also carry metadata.route.type for built-in CRUD/IAM mapping.

Auto-generated CRUD routes receive built-in runtime actions automatically:

  • create
  • delete
  • get
  • getList
  • partialUpdate
  • update

Custom secured routes should declare their own domain-specific action strings:

typescript
@ApiMethod({
	metadata: {
		resource: {
			action: "update.promote",
			entity: UserEntity,
		},
		route: {
			method: RequestMethod.POST,
			path: ":id/promote",
		},
		security: {
			authorization: { mode: EApiAuthorizationMode.HOOKS },
		},
		response: {
			status: HttpStatus.OK,
			type: UserResponseDto,
		},
	},
})
public promote(@Param("id") id: string) {
	return this.service.promote(id);
}

The same metadata.resource.action value is what hooks receive as context.action and what IAM turns into a namespaced action such as admin:user:update.promote.

Use @ApiRouteCustom(...) when a custom controller route should also participate

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言