NestJs CRUD
repository·master·Indexed 26 days ago
https://github.com/nestjsx/crudA microframework for NestJS that automates the creation of RESTful CRUD endpoints. It provides powerful query parsing for filtering, pagination, sorting, and relations across different databases. The project includes the core @nestjsx/crud package, @nestjsx/crud-request for request building and parsing, and @nestjsx/crud-typeorm for TypeORM-specific database operations.
What's inside @nestjsx/crud
- NestJs CRUD is a microframework designed for building RESTful APIs with NestJS. It provides full-featured controllers and services that are database and service agnostic, allowing for rapid development of CRUD functionality.
Configure joins and selection in TypeOrmCrudService
masterThe
TypeOrmCrudServiceuses thecreateBuildermethod to translateCrudRequestoptions into a TypeORMSelectQueryBuilder.- Joins: You can specify joins via
options.query.join. If a join is marked aseager: truein the configuration, it will be applied automatically. Otherwise, joins are applied based on theparsed.joinarray in the request. - Selection: You can restrict returned columns using
query.fieldsor viaoptions.allow/options.exclude. The service always ensures primary columns are included in the selection. - Soft Delete: If your entity contains a column marked with
@DeleteDateColumn, the service supports soft deletion. You can toggle this behavior usingoptions.query.softDeleteand include deleted records usingparsed.includeDeleted === 1.
- Joins: You can specify joins via
Configure TypeORM connection options
masterWhen setting up
@nestjsx/crud-typeorm, you can define connection settings usingTypeOrmModuleOptions. The configuration supports different database types (e.g.,postgres,mysql) and can be driven by environment variables for connection type and logging behavior.Key configuration properties:
type: The database engine (e.g.,'postgres','mysql'). Can be set viaprocess.env.TYPEORM_CONNECTION.logging: Boolean flag to enable/disable logging. Can be controlled viaprocess.env.TYPEORM_LOGGING(expects a numeric string like'1'for true).entities: An array of paths to entity files (e.g.,join(__dirname, './**/*.entity{.ts,.js}')).
Identify the NestJs CRUD packages
masterThe project is split into several specialized packages depending on your needs:
@nestjsx/crud: The core package. It provides the@Crud()decorator for automatic endpoint generation, global configuration, validation, and helper decorators.@nestjsx/crud-request: A request builder/parser package. It includesRequestQueryBuilderfor frontend usage andRequestQueryParserfor backend handling and validation of query/path parameters.@nestjsx/crud-typeorm: A TypeORM-specific package. It provides theTypeOrmCrudServicewhich contains methods for standard CRUD database operations.
Handle RequestQueryException with BadRequestException
masterWhen using theCrudRequestInterceptor, if the incoming query fails validation or parsing, the interceptor catchesRequestQueryExceptionand rethrows it as a NestJSBadRequestException. This ensures that malformed CRUD queries result in a standard400 Bad Requestresponse instead of internal server errors.Handle RequestQueryException errors
masterTheRequestQueryExceptionis thrown by the@nestjsx/crudpackages when a request query is invalid. This exception extends the standard JavaScriptErrorclass and carries a specific error message describing the invalid query parameters.Configure route parameter options with ParamsOptions
masterThe
ParamsOptionsinterface allows you to define configuration for route parameters using a dictionary where keys are parameter names and values areParamOptionobjects. This is used to control how specific fields are handled in CRUD operations.Each
ParamOptioncan specify:field: The underlying database field name associated with the parameter.type: The data type of the parameter (usingParamOptionTypefrom@nestjsx/crud-request).enum: An enumeration type for the parameter (usingSwaggerEnumType).primary: A boolean indicating if this is a primary parameter.disabled: A boolean to disable the parameter.
export interface ParamsOptions { [key: string]: ParamOption; } export interface ParamOption { field?: string; type?: ParamOptionType; enum?: SwaggerEnumType; primary?: boolean; disabled?: boolean; }Use TypeOrmCrudService for CRUD operations
masterThe
TypeOrmCrudService<T>is the TypeORM implementation of theCrudService. It provides asynchronous methods to perform standard CRUD operations using a TypeORMRepository.Key methods include:
getMany(req: CrudRequest): Retrieves multiple records based on the request parameters (filtering, sorting, pagination, joins).getOne(req: CrudRequest): Retrieves a single record.createOne(req: CrudRequest, dto: T | Partial<T>): Creates a single record.createMany(req: CrudRequest, dto: CreateManyDto<T | Partial<T>>): Creates multiple records in bulk (using a chunk size of 50).updateOne(req: CrudRequest, dto: T | Partial<T>): Updates an existing record.replaceOne(req: CrudRequest, dto: T | Partial<T>): Replaces an existing record.deleteOne(req: CrudRequest): Deletes a record (supports soft delete if the entity has a delete column andsoftDelete: trueis in the query options).recoverOne(req: CrudRequest): Recovers a soft-deleted record.
Use TypeOrmCrudService from @nestjsx/crud-typeorm
masterThe@nestjsx/crud-typeormpackage providesTypeOrmCrudService, which is the primary service used to integrate NestJS CRUD functionality with TypeORM. This service handles the mapping between CRUD requests and TypeORM repository operations.Validate query joins
masterUsevalidateJointo validate aQueryJoinobject. It ensures the join is an object with a validfieldstring. If aselectproperty is provided, it must be an array of strings.Define Query Filters using QueryFilter and QueryFilterArr
masterWhen constructing filters for CRUD requests, you can use either the
QueryFilterobject or theQueryFilterArrtuple format.QueryFilterrequires afield(string), anoperator(fromComparisonOperator), and an optionalvalue.QueryFilterArris a tuple in the format:[field, operator, value?].Configure RecoverOne route options
masterTheRecoverOneRouteOptionsinterface extendsBaseRouteOptionsand includes thereturnRecoveredproperty. When set totrue, the API will return the entity that was just recovered.