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 一个用于在 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
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.
CorrelationIDResponseBodyInterceptor to correlate requests and logs.Install NestJS-Crud-Automator using your preferred package manager:
# Using npm
npm install @elsikora/nestjs-crud-automator
# Using yarn
yarn add @elsikora/nestjs-crud-automator
# Using pnpm
pnpm add @elsikora/nestjs-crud-automatorVersion 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.
Make sure you have the following dependencies installed in your NestJS project:
@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>=0.3.20>=5.8.5class-validator >=0.15.1class-transformer >=0.5.1lodash >=4.18.1You might need to install these peer dependencies if they're not already in your project:
npm install @nestjs/common @nestjs/core @nestjs/passport @nestjs/platform-fastify @nestjs/swagger @nestjs/throttler typeorm class-transformer class-validator fastify lodashFirst, 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.
Create a service with the ApiService decorator to add CRUD operations:
…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.
Add custom validators to your DTOs:
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) {}
}Automatically transform request data:
…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.
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:
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 now has two first-class modes:
hooks: auto-discovered @ApiAuthorizationPolicy({ entity }) classesiam: 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.
@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:
createdeletegetgetListpartialUpdateupdateCustom secured routes should declare their own domain-specific action strings:
@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,或尚未同步最近议题。