### Prepare and Start TypeORM Example Source: https://github.com/nestjsx/crud/wiki/Home Commands to prepare the TypeORM database and start the example project. ```shell yarn db:prepare:typeorm yarn start:typeorm ``` -------------------------------- ### GET All Records Request Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Example of a GET request to fetch multiple records, including common query parameters for filtering, sorting, and pagination. ```http GET /users?fields=id,name&limit=10&page=1 Accept: application/json ``` -------------------------------- ### GET All Records Filter Examples Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Demonstrates various ways to filter records using query parameters, including simple equality, range, OR conditions, and combinations with sorting and pagination. ```http GET /users?filter=status||$eq||active ``` ```http GET /users?filter=age||$gte||18&filter=age||$lte||65 ``` ```http GET /users?or=role||$eq||admin&or=role||$eq||moderator ``` ```http GET /users?filter=email||$cont||@example.com&sort=createdAt,DESC&limit=20&page=1 ``` -------------------------------- ### Select Fields Example Source: https://github.com/nestjsx/crud/wiki/Requests Use the 'fields' parameter to specify which fields to include in the GET request response. ```http ?fields=email,name ``` -------------------------------- ### GET Single Record Response Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Example JSON response for a successful request to fetch a single record. ```json { "id": 123, "name": "John Doe", "email": "john@example.com", "roles": [ { "id": 1, "name": "admin" } ] } ``` -------------------------------- ### Example API Endpoints for User Management Source: https://github.com/nestjsx/crud/blob/master/_autodocs/README.md Illustrates common HTTP requests for interacting with the generated user endpoints. These examples cover fetching, creating, updating, and deleting user resources. ```bash # Get all users (paginated) GET /users?limit=10&page=1 # Get all active users GET /users?filter=status||$eq||active # Get a single user GET /users/550e8400-e29b-41d4-a716-446655440000 # Create a user POST /users { "name": "John Doe", "email": "john@example.com", "status": "active" } # Update a user PATCH /users/550e8400-e29b-41d4-a716-446655440000 { "email": "newemail@example.com" } # Delete a user DELETE /users/550e8400-e29b-41d4-a716-446655440000 ``` -------------------------------- ### GET Single Record Request Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Example of a GET request to fetch a single record by its primary key, with optional field selection and relation loading. ```http GET /users/123 Accept: application/json ``` -------------------------------- ### Users Controller Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-decorators.md This example demonstrates a complete UsersController using Nestjsx/crud decorators to manage User resources. It includes overriding default CRUD methods, applying authentication guards, and defining custom DTOs for create and update operations. ```APIDOC ## GET /users ### Description Retrieves a list of users, supporting pagination and eager loading of related entities like roles. Authentication is required. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **page** (number) - Optional - The page number for pagination. - **limit** (number) - Optional - The number of items per page. - **fields** (string) - Optional - Comma-separated list of fields to include in the response. - **sort** (string) - Optional - Field to sort by (e.g., `name:ASC`). - **filter** (string) - Optional - Filter criteria (e.g., `name:John`). - **join** (string) - Optional - Fields to eagerly load (e.g., `roles`). ### Response #### Success Response (200) - **data** (array) - An array of user objects. - **total** (number) - The total number of users matching the query. - **page** (number) - The current page number. - **pageCount** (number) - The total number of pages. ## GET /users/:id ### Description Retrieves a single user by their ID. Authentication is required. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. #### Query Parameters - **fields** (string) - Optional - Comma-separated list of fields to include in the response. - **join** (string) - Optional - Fields to eagerly load (e.g., `roles`). ### Response #### Success Response (200) - **id** (string) - The user's unique identifier. - **username** (string) - The user's username. - **email** (string) - The user's email address. - **roles** (array) - An array of roles associated with the user. ## POST /users ### Description Creates a new user. Requires authentication and uses `CreateUserDto` for validation. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. - **organizationId** (string) - Required - The ID of the organization the user belongs to. - **role** (string) - Required - The role of the user (e.g., 'admin', 'user'). ### Response #### Success Response (201) - **id** (string) - The unique identifier of the newly created user. - **username** (string) - The username of the new user. - **email** (string) - The email address of the new user. - **organizationId** (string) - The organization ID associated with the new user. - **role** (string) - The role assigned to the new user. ## PUT /users/:id ### Description Updates an existing user by their ID. Requires authentication and uses `UpdateUserDto` for validation. ### Method PUT ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to update. #### Request Body - **username** (string) - Optional - The updated username. - **email** (string) - Optional - The updated email address. - **role** (string) - Optional - The updated role of the user. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the updated user. - **username** (string) - The updated username. - **email** (string) - The updated email address. - **organizationId** (string) - The organization ID associated with the user. - **role** (string) - The updated role assigned to the user. ## DELETE /users/:id ### Description Deletes a user by their ID. Requires authentication. ### Method DELETE ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to delete. ### Response #### Success Response (204) No Content. Indicates successful deletion. ``` -------------------------------- ### Install and Run Tests Source: https://github.com/nestjsx/crud/wiki/Home Commands to clone the repository, set up Docker, bootstrap dependencies, build the project, and run tests. ```shell docker-compose up -d yarn bootstrap yarn build yarn test ``` -------------------------------- ### Install @nestjsx/crud-typeorm Source: https://github.com/nestjsx/crud/wiki/ServiceTypeorm Install the necessary packages for TypeORM integration. Ensure you have @nestjs/typeorm and typeorm installed. ```shell npm i @nestjsx/crud-typeorm @nestjs/typeorm typeorm ``` -------------------------------- ### Complete Controller Example with CRUD Decorators Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-decorators.md This example demonstrates a complete NestJS controller using @nestjsx/crud decorators for managing User resources. It includes configuration for model, DTOs, query parameters, route overrides, and authentication. ```typescript import { Controller, UseInterceptors, UseGuards, HttpCode, HttpStatus, } from '@nestjs/common'; import { Crud, CrudAuth, Override, ParsedRequest, ParsedBody, FeatureAction, } from '@nestjsx/crud'; import { JwtAuthGuard } from './auth/jwt-auth.guard'; import { User } from './user.entity'; import { UsersService } from './users.service'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; @Crud({ model: { type: User }, dto: { create: CreateUserDto, update: UpdateUserDto, }, query: { limit: 10, maxLimit: 100, alwaysPaginate: true, join: { roles: { eager: true }, organization: { eager: false }, }, }, routes: { getManyBase: { decorators: [UseGuards(JwtAuthGuard)], }, createOneBase: { decorators: [UseGuards(JwtAuthGuard)], returnShallow: false, }, deleteOneBase: { returnDeleted: true, }, }, }) @CrudAuth({ property: 'user', filter: (req) => ({ organizationId: req.user.organizationId, }), groups: (req) => req.user.role === 'admin' ? ['admin'] : ['user'], }) @UseGuards(JwtAuthGuard) @Controller('users') export class UsersController { constructor(private service: UsersService) {} @Override('getManyBase') @FeatureAction('users.list') async getManyBase(@ParsedRequest() req: CrudRequest) { return this.service.getMany(req); } @Override('getOneBase') @FeatureAction('users.view') async getOneBase(@ParsedRequest() req: CrudRequest) { return this.service.getOne(req); } @Override('createOneBase') @FeatureAction('users.create') @HttpCode(HttpStatus.CREATED) async createOneBase( @ParsedRequest() req: CrudRequest, @ParsedBody() dto: CreateUserDto, ) { return this.service.createOne(req, dto); } @Override('updateOneBase') @FeatureAction('users.update') async updateOneBase( @ParsedRequest() req: CrudRequest, @ParsedBody() dto: UpdateUserDto, ) { return this.service.updateOne(req, dto); } @Override('deleteOneBase') @FeatureAction('users.delete') @HttpCode(HttpStatus.NO_CONTENT) async deleteOneBase(@ParsedRequest() req: CrudRequest) { return this.service.deleteOne(req); } } ``` -------------------------------- ### Install @nestjsx/crud-request Source: https://github.com/nestjsx/crud/blob/master/packages/crud-request/README.md Install the @nestjsx/crud-request package using npm. ```shell npm i @nestjsx/crud-request ``` -------------------------------- ### Sort Validation Example in TypeScript Source: https://github.com/nestjsx/crud/blob/master/_autodocs/errors.md Shows how to validate sort parameters, with examples of correct and incorrect sort orders. ```typescript validateSort(sort: QuerySort): void ``` ```typescript { field: 'createdAt', order: 'ASC' } // ✓ { field: 'name', order: 'DESC' } // ✓ { field: 'name', order: 'INVALID' } // ✗ ``` -------------------------------- ### Usage Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-decorator.md An example demonstrating how to use the @Crud() decorator in a NestJS controller with TypeORM. ```APIDOC ## Usage Example ```typescript import { Controller } from '@nestjs/common'; import { Crud } from '@nestjsx/crud'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; @Crud({ model: { type: User, }, dto: { create: CreateUserDto, update: UpdateUserDto, }, query: { limit: 10, maxLimit: 100, alwaysPaginate: true, join: { roles: { eager: true, required: false, }, }, }, routes: { exclude: ['deleteAll', 'recoverOne'], getManyBase: { decorators: [/* Custom decorators */], }, }, }) @Controller('users') export class UsersController { constructor( @InjectRepository(User) private repo: Repository, ) {} get service(): TypeOrmCrudService { return new TypeOrmCrudService(this.repo); } } ``` ``` -------------------------------- ### Example NotFoundException Response Source: https://github.com/nestjsx/crud/blob/master/_autodocs/errors.md Shows the JSON response for a NotFoundException, indicating that a requested resource could not be found. ```json { "statusCode": 404, "message": "User not found", "error": "Not Found" } ``` -------------------------------- ### Install @nestjsx/crud Packages Source: https://github.com/nestjsx/crud/blob/master/packages/crud/README.md Install the core @nestjsx/crud package along with class-transformer and class-validator for validation. ```shell npm i @nestjsx/crud class-transformer class-validator ``` -------------------------------- ### GET All Records Response (Paginated) Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Example JSON response for a paginated request to fetch multiple records. ```json { "data": [ { "id": 1, "name": "John Doe" }, { "id": 2, "name": "Jane Smith" } ], "count": 2, "total": 47, "page": 1, "pageCount": 5 } ``` -------------------------------- ### GET All Records Response (Array) Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Example JSON response when pagination is not enabled or requested for fetching multiple records. ```json [ { "id": 1, "name": "John Doe" }, { "id": 2, "name": "Jane Smith" } ] ``` -------------------------------- ### Complete Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/request-query-builder.md Demonstrates how to use the Request Query Builder to construct a complex query string, including setting options, filters, joins, sorting, and pagination. ```APIDOC ## Complete Example ```typescript import { RequestQueryBuilder } from '@nestjsx/crud-request'; // Configure global options RequestQueryBuilder.setOptions({ delim: '||', delimStr: ',', }); // Build a complex query const queryString = RequestQueryBuilder.create() .select(['id', 'name', 'email', 'createdAt']) .setFilter([ { field: 'status', operator: '$eq', value: 'active' }, { field: 'email', operator: '$cont', value: '@example.com' }, ]) .setOr({ field: 'role', operator: '$in', value: ['admin', 'moderator'] }) .setJoin([ { field: 'roles', select: ['id', 'name'] }, { field: 'profile' }, ]) .sortBy([ { field: 'createdAt', order: 'DESC' }, { field: 'name', order: 'ASC' }, ]) .setLimit(20) .setPage(1) .query(); // queryString can now be used in HTTP requests // GET /api/users?fields=id,name,email,createdAt&filter=...&sort=...&page=1&limit=20 ``` ``` -------------------------------- ### Complete Request Query Parsing Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/request-query-parser.md Demonstrates parsing query strings, path parameters, and authentication persistence. Invalid input will throw a RequestQueryException. ```typescript import { RequestQueryParser } from '@nestjsx/crud-request'; // Parse query string and path parameters const parser = RequestQueryParser.create(); parser.parseQuery({ fields: 'id,name,email,createdAt', filter: 'status||$eq||active', or: 'role||$in||admin,moderator', join: 'roles||id,name||permissions', sort: 'createdAt,DESC', limit: '20', page: '1', cache: '300', }); parser.parseParams( { id: '123' }, { id: { field: 'userId', type: 'number', primary: true, }, }, ); parser.setAuthPersist({ userId: 456, tenantId: 1 }); const parsed = parser.getParsed(); // { // fields: ['id', 'name', 'email', 'createdAt'], // filter: [{ field: 'status', operator: '$eq', value: 'active' }], // or: [{ field: 'role', operator: '$in', value: ['admin', 'moderator'] }], // join: [{ field: 'roles', select: ['id', 'name'] }, { field: 'permissions' }], // sort: [{ field: 'createdAt', order: 'DESC' }], // limit: 20, // page: 1, // cache: 300, // paramsFilter: [{ field: 'userId', operator: '$eq', value: 123 }], // authPersist: { userId: 456, tenantId: 1 }, // search: { $and: [...] }, // ... // } ``` -------------------------------- ### Common Filter Operator Examples Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Illustrates various common filter operators like $eq, $gt, $gte, $cont, $in, $isnull, $starts, and $eqL for different data types and conditions. ```plaintext name||$eq||john ``` ```plaintext age||$gt||18 ``` ```plaintext age||$gte||18 ``` ```plaintext email||$cont||example.com ``` ```plaintext status||$in||active,pending ``` ```plaintext deletedAt||$isnull ``` ```plaintext email||$starts||admin ``` ```plaintext name||$eqL||JOHN ``` -------------------------------- ### Multi-Filter Query Examples Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Demonstrates how to construct complex queries using multiple filter parameters, including combining filters with AND logic and using OR conditions. ```plaintext GET /users?filter=status||$eq||active&filter=age||$gte||18 ``` ```plaintext GET /users?or=role||$eq||admin&or=role||$eq||moderator&filter=status||$eq||active ``` -------------------------------- ### UUID Validation Example in TypeScript Source: https://github.com/nestjsx/crud/blob/master/_autodocs/errors.md Demonstrates the validation of UUID formats, providing examples of valid and invalid UUID strings. ```typescript validateUUID(value: string): void ``` ```typescript '550e8400-e29b-41d4-a716-446655440000' // ✓ 'invalid-uuid' // ✗ ``` -------------------------------- ### Search with AND Condition (Shorthand) Example Source: https://github.com/nestjsx/crud/wiki/Requests A shorthand syntax for combining multiple AND conditions in the 's' search parameter. ```http ?s={"isActive": true, "createdAt": {"$ne": "2008-10-01T17:04:32"}} ``` -------------------------------- ### Query Parser Configuration Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/configuration.md Configure global request query builder options, including delimiters and parameter name mappings for fields, search, filter, and sorting. ```typescript { queryParser: { delim: '||', delimStr: ',', paramNamesMap: { fields: ['fields', 'select'], search: 's', filter: 'filter', or: 'or', join: 'join', sort: 'sort', limit: ['limit', 'per_page'], offset: 'offset', page: 'page', cache: 'cache', includeDeleted: 'include_deleted', }, }, } ``` -------------------------------- ### Field Validation Example in TypeScript Source: https://github.com/nestjsx/crud/blob/master/_autodocs/errors.md Shows the signature for validating fields and provides examples of valid and invalid inputs for selecting query fields. ```typescript validateFields(fields: QueryFields): void ``` ```typescript qb.select(['id', 'name', 'email']); // ✓ qb.select([]); // ✗ Cannot be empty if provided ``` -------------------------------- ### CustomUserService Methods Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-service.md Example implementation of a custom CRUD service for User entities, demonstrating overrides for standard CRUD operations. ```APIDOC ## Custom Service Implementation Example This section provides an example of how to extend the `CrudService` to implement custom logic for CRUD operations on `User` entities. ### getMany(req: CrudRequest): Promise | User[]> #### Description Retrieves a collection of users, with support for pagination, sorting, and filtering. #### Parameters - **req** (`CrudRequest`) - Required - The request object containing parsed query parameters and options. #### Returns A promise that resolves to either a paginated response containing user data and total count, or an array of user objects. ### getOne(req: CrudRequest): Promise #### Description Retrieves a single user based on the provided request criteria. #### Parameters - **req** (`CrudRequest`) - Required - The request object containing parsed query parameters and options. #### Returns A promise that resolves to the found user object. ### createOne(req: CrudRequest, dto: Partial): Promise #### Description Creates a new user with the provided data. #### Parameters - **req** (`CrudRequest`) - Required - The request object. - **dto** (`Partial`) - Required - An object containing the user data to create. #### Returns A promise that resolves to the newly created user object. ### createMany(req: CrudRequest, dto: CreateManyDto): Promise #### Description Creates multiple users in a single operation. #### Parameters - **req** (`CrudRequest`) - Required - The request object. - **dto** (`CreateManyDto`) - Required - An object containing an array of user data to create. #### Returns A promise that resolves to an array of the newly created user objects. ### updateOne(req: CrudRequest, dto: Partial): Promise #### Description Updates an existing user with the provided data. #### Parameters - **req** (`CrudRequest`) - Required - The request object. - **dto** (`Partial`) - Required - An object containing the fields to update. #### Returns A promise that resolves to the updated user object. ### replaceOne(req: CrudRequest, dto: Partial): Promise #### Description Replaces an existing user entirely with the provided data. #### Parameters - **req** (`CrudRequest`) - Required - The request object. - **dto** (`Partial`) - Required - An object containing the complete new data for the user. #### Returns A promise that resolves to the replaced user object. ### deleteOne(req: CrudRequest): Promise #### Description Deletes a user. #### Parameters - **req** (`CrudRequest`) - Required - The request object. #### Returns A promise that resolves to `undefined` if the deleted item is not returned, or the deleted user object if configured to return deleted items. ### recoverOne(req: CrudRequest): Promise #### Description Recovers a previously soft-deleted user. #### Parameters - **req** (`CrudRequest`) - Required - The request object. #### Returns A promise that resolves to `undefined` or the recovered user object. ### buildWhere(filters: any, search: any): any #### Description Internal helper to build the WHERE clause for database queries. ### buildSort(sorts: any): any #### Description Internal helper to build the ORDER BY clause for database queries. ``` -------------------------------- ### GET / Source: https://github.com/nestjsx/crud/blob/master/_autodocs/INDEX.md Retrieves a list of all records. This is the base endpoint for fetching multiple records. ```APIDOC ## GET / ### Description Retrieves a list of all records. This is the base endpoint for fetching multiple records. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **(Various)** - Optional - Query parameters for filtering, sorting, and pagination. ### Response #### Success Response (200) - **(Array of Records)** - Description of the returned records. ``` -------------------------------- ### Example Usage of SFields Type Source: https://github.com/nestjsx/crud/blob/master/_autodocs/types.md Shows how to define a search query using SFields, including field-specific conditions and an OR group. ```typescript const search: SFields = { name: { $cont: 'john' }, age: { $gte: 18 }, $or: [ { status: 'active' }, { status: 'pending' }, ], }; ``` -------------------------------- ### Example Usage of CrudRoutesFactory.create() Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-routes-factory.md Demonstrates how to create an instance of CrudRoutesFactory with a controller and basic CRUD options. This is typically done internally by the @Crud() decorator. ```typescript const factory = CrudRoutesFactory.create(MyController, { model: { type: User }, query: { limit: 10 }, }); ``` -------------------------------- ### Filter by Boolean and String Equality Example Source: https://github.com/nestjsx/crud/wiki/Requests Demonstrates filtering by both a boolean and a string field using the 'filter' parameter. Multiple filters are combined with AND logic. ```http ?filter=isVillain||$eq||false&filter=city||$eq||Arkham ``` -------------------------------- ### Configure Query Parameters for GET Requests Source: https://github.com/nestjsx/crud/wiki/Controllers Set options for GET requests, including allowed/excluded fields, fields to persist, join configurations, sorting, and pagination limits. ```typescript @Crud({ ... query?: { allow?: string[]; exclude?: string[]; persist?: string[]; filter?: QueryFilterOption; join?: JoinOptions; sort?: QuerySort[]; limit?: number; maxLimit?: number; cache?: number | false; alwaysPaginate?: boolean; }, ... }) ``` -------------------------------- ### Usage Example: Overriding getManyBase Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-decorators.md Demonstrates how to use the @Override decorator to customize the 'getManyBase' route. This example adds a computed 'displayName' property to each user returned. ```typescript import { Crud, Override } from '@nestjsx/crud'; import { Controller, Get, Param } from '@nestjs/common'; @Crud({ model: { type: User }, routes: { getManyBase: { interceptors: [], decorators: [] }, }, }) @Controller('users') export class UsersController { constructor(private service: UsersService) {} // Override the auto-generated getMany route with custom logic @Override('getManyBase') async getManyBase(@ParsedRequest() req: CrudRequest) { const result = await this.service.getMany(req); // Custom logic after fetch if (Array.isArray(result.data)) { result.data = result.data.map(user => ({ ...user, // Add computed property displayName: `${user.firstName} ${user.lastName}`, })); } return result; } // Create a custom route alongside CRUD routes @Get('by-email/:email') async getUserByEmail(@Param('email') email: string) { return this.service.findOne({ where: { email } }); } } ``` -------------------------------- ### Example: Implementing UsersService with TypeOrmCrudService Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/typeorm-crud-service.md Demonstrates how to extend TypeOrmCrudService in a NestJS application by injecting the TypeORM repository for the User entity. ```typescript import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { User } from './user.entity'; @Injectable() export class UsersService extends TypeOrmCrudService { constructor( @InjectRepository(User) repo: Repository, ) { super(repo); } } ``` -------------------------------- ### Example Usage of getPrimaryParams Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-service.md Demonstrates how to call the getPrimaryParams method with request options to obtain primary key field names. The output varies based on whether a composite or single key is used. ```typescript const primaryParams = this.getPrimaryParams(req.options); // Returns: ['userId', 'tenantId'] for composite key // Returns: ['id'] for single key ``` -------------------------------- ### Authentication Global Options Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/configuration.md Configure default authentication behavior, specifying the request property for user information and custom class-transformer options or serialization groups per request. ```typescript { auth: { property: 'user', groups: (req) => req.user?.role === 'admin' ? ['admin'] : ['user'], classTransformOptions: (req) => ({ strategy: 'excludeAll', }), }, } ``` -------------------------------- ### Example Usage of SCondition Type (Implicit AND) Source: https://github.com/nestjsx/crud/blob/master/_autodocs/types.md Demonstrates an implicit AND condition where multiple field-value pairs must all match. ```typescript // Implicit AND const search: SCondition = { status: 'active', role: { $in: ['admin', 'moderator'] }, }; ``` -------------------------------- ### Search with AND Condition Example Source: https://github.com/nestjsx/crud/wiki/Requests Use the 's' parameter with a JSON string to search entities with multiple AND conditions. ```http ?s={"$and": [{"isActive": true}, {"createdAt": {"$ne": "2008-10-01T17:04:32"}}]} ``` -------------------------------- ### Example Usage of SCondition Type (Explicit OR) Source: https://github.com/nestjsx/crud/blob/master/_autodocs/types.md Shows how to construct an explicit OR condition using the '$or' key, where at least one condition must match. ```typescript // Explicit OR const search: SCondition = { $or: [ { role: 'admin' }, { role: 'moderator' }, ], }; ``` -------------------------------- ### Limit and Offset Pagination Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Use 'limit' and 'offset' query parameters to control the number of items returned and the starting point of the results. ```http GET /users?limit=10&offset=20 ``` -------------------------------- ### Join Validation Example in TypeScript Source: https://github.com/nestjsx/crud/blob/master/_autodocs/errors.md Demonstrates the validation rules for join operations, including correct and incorrect configurations for join fields and selections. ```typescript validateJoin(join: QueryJoin): void ``` ```typescript { field: 'roles', select: ['id', 'name'] } // ✓ { field: 'roles' } // ✓ { field: '', select: ['id'] } // ✗ Empty field { field: 'roles', select: 'invalid' } // ✗ Select not array ``` -------------------------------- ### Example BadRequestException Response Source: https://github.com/nestjsx/crud/blob/master/_autodocs/errors.md Illustrates the JSON structure of a BadRequestException, typically returned when request data is invalid or missing. ```json { "statusCode": 400, "message": "Empty data. Nothing to save.", "error": "Bad Request" } ``` -------------------------------- ### Example Usage of SField Type Source: https://github.com/nestjsx/crud/blob/master/_autodocs/types.md Demonstrates assigning a simple string value or an operator object to an SField type. ```typescript // Simple value const field: SField = 'active'; ``` ```typescript // Operator object const field: SField = { $eq: 'active', $or: { $eq: 'pending' }, }; ``` -------------------------------- ### Parameter Option Validation in TypeScript Source: https://github.com/nestjsx/crud/blob/master/_autodocs/errors.md Details the validation for parameter option configurations, noting that an error is thrown for invalid setups. ```typescript validateParamOption(options: ParamsOptions, name: string): void ``` -------------------------------- ### Basic Crud Decorator Usage Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-decorator.md Demonstrates how to apply the @Crud() decorator to a NestJS controller, configuring model, DTOs, query options, and route exclusions. ```typescript import { Controller } from '@nestjs/common'; import { Crud } from '@nestjsx/crud'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; @Crud({ model: { type: User, }, dto: { create: CreateUserDto, update: UpdateUserDto, }, query: { limit: 10, maxLimit: 100, alwaysPaginate: true, join: { roles: { eager: true, required: false, }, }, }, routes: { exclude: ['deleteAll', 'recoverOne'], getManyBase: { decorators: [/* Custom decorators */], }, }, }) @Controller('users') export class UsersController { constructor( @InjectRepository(User) private repo: Repository, ) {} get service(): TypeOrmCrudService { return new TypeOrmCrudService(this.repo); } } ``` -------------------------------- ### Create Many Resources Request Body Example Source: https://github.com/nestjsx/crud/wiki/Controllers This JSON structure is used for the request body when creating multiple resources in bulk. It should be an array of resource objects, potentially including nested relational resources. ```json { "bulk": [{ "name": "Batman" }, { "name": "Batgirl" }] } ``` -------------------------------- ### Complete Example of TypeORM CRUD Service Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/typeorm-crud-service.md Demonstrates how to extend TypeOrmCrudService to add custom business logic for fetching multiple entities. It shows how to override the getMany method for pre-processing filters and post-processing results. ```typescript import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { User } from './user.entity'; @Injectable() export class UsersService extends TypeOrmCrudService { constructor( @InjectRepository(User) repo: Repository, ) { super(repo); } // Override to add custom business logic async getMany(req: CrudRequest) { // Custom pre-processing console.log('Fetching users with filters:', req.parsed.filter); const result = await super.getMany(req); // Custom post-processing if (Array.isArray(result.data || result)) { // Apply custom transformation } return result; } } ``` -------------------------------- ### Cache Configuration Source: https://github.com/nestjsx/crud/wiki/Controllers Enable caching for GET responses by setting the 'cache' option in milliseconds. Caching can be reset using the 'cache=0' query parameter. ```typescript { cache: 2000, } ``` -------------------------------- ### CRUD Routes Factory createRoutes() Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-routes-factory.md Illustrates how a route handler is generated for the `getOneBase` route, assigning an async function to the controller prototype that utilizes the service layer. ```typescript // Generated for getOneBase controller.getOneBase = async function(req: CrudRequest) { return this.service.getOne(req); }; ``` -------------------------------- ### GET Single Record Error Response (Not Found) Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Example error response when a requested record is not found. ```http Status: 404 Not Found { "statusCode": 404, "message": "User not found", "error": "Not Found" } ``` -------------------------------- ### FeatureAction Decorator Usage Example Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-decorators.md Illustrates applying the @FeatureAction decorator to methods for listing, creating, and deleting users. It also shows how to combine it with other decorators like @Override and @UseGuards. ```typescript import { FeatureAction, Override } from '@nestjsx/crud'; import { Controller, UseGuards } from '@nestjs/common'; @Controller('users') export class UsersController { @Override('getManyBase') @FeatureAction('users.list') async getManyBase(@ParsedRequest() req: CrudRequest) { return this.service.getMany(req); } @Override('createOneBase') @FeatureAction('users.create') async createOneBase( @ParsedRequest() req: CrudRequest, @ParsedBody() dto: CreateUserDto, ) { return this.service.createOne(req, dto); } @Override('deleteOneBase') @FeatureAction('users.delete') @UseGuards(AdminGuard) async deleteOneBase(@ParsedRequest() req: CrudRequest) { return this.service.deleteOne(req); } } ``` -------------------------------- ### Usage Example for @ParsedRequest Decorator Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/crud-decorators.md Demonstrates how to use the @ParsedRequest decorator in a NestJS controller to inject parsed request data into controller methods for GET requests. ```typescript import { ParsedRequest } from '@nestjsx/crud'; import { Controller, Get } from '@nestjs/common'; @Controller('users') export class UsersController { constructor(private service: UsersService) {} @Get() async getMany(@ParsedRequest() req: CrudRequest) { // req.parsed contains parsed query parameters // req.options contains CRUD configuration return this.service.getMany(req); } @Get(':id') async getOne(@ParsedRequest() req: CrudRequest) { return this.service.getOne(req); } } ``` -------------------------------- ### Create RequestQueryParser Instance Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/request-query-parser.md Demonstrates how to create a new RequestQueryParser instance and use it to parse query and path parameters. ```typescript const parser = RequestQueryParser.create(); parser.parseQuery(req.query); parser.parseParams(req.params, paramOptions); const parsed = parser.getParsed(); ``` -------------------------------- ### Create User Source: https://github.com/nestjsx/crud/blob/master/_autodocs/README.md Creates a new user with the provided details. ```APIDOC ## POST /users ### Description Creates a new user with the provided details. ### Method POST ### Endpoint /users ### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **status** (string) - Required - The status of the user. ### Request Example ```json { "name": "John Doe", "email": "john@example.com", "status": "active" } ``` ``` -------------------------------- ### CreateManyDto Source: https://github.com/nestjsx/crud/blob/master/_autodocs/types.md Wrapper for bulk create operations, containing an array of items to be created. ```APIDOC ## CreateManyDto ### Description Wrapper for bulk create operations. ### Type Definition ```typescript interface CreateManyDto { bulk: T[]; } ``` ### Properties - **bulk** (`T[]`) - Required - Array of items to create ``` -------------------------------- ### Exclude Specific Fields from GET Responses Source: https://github.com/nestjsx/crud/wiki/Controllers Specify an array of fields to be excluded from GET responses and not queried from the database. ```typescript { exclude: ["accessToken"]; } ``` -------------------------------- ### Persist Specific Fields in GET Responses Source: https://github.com/nestjsx/crud/wiki/Controllers Define an array of fields that will always be included in GET responses, regardless of other query configurations. ```typescript { persist: ["createdAt"]; } ``` -------------------------------- ### Allow Specific Fields in GET Requests Source: https://github.com/nestjsx/crud/wiki/Controllers Define an array of fields that are permitted in GET requests. If this array is empty or undefined, all fields are allowed. ```typescript { allow: ["name", "email"]; } ``` -------------------------------- ### RequestQueryParser.create() Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/request-query-parser.md Creates a new instance of the RequestQueryParser class. This is the entry point for using the parser. ```APIDOC ## Static Methods ### create() ```typescript static create(): RequestQueryParser ``` Creates a new RequestQueryParser instance. **Returns:** A new `RequestQueryParser` instance. **Example:** ```typescript const parser = RequestQueryParser.create(); parser.parseQuery(req.query); parser.parseParams(req.params, paramOptions); const parsed = parser.getParsed(); ``` ``` -------------------------------- ### Build Query String with Chaining Methods Source: https://github.com/nestjsx/crud/wiki/Requests Compose a query string by chaining methods on a RequestQueryBuilder instance. This example demonstrates setting search conditions, selecting fields, joining related entities, sorting, pagination, and cache reset. ```typescript import { RequestQueryBuilder, CondOperator } from "@nestjsx/crud-request"; const qb = RequestQueryBuilder.create(); // set search qb.search({ $or: [ { foo: { $notnull: true }, baz: 1 }, { bar: { $ne: "test" } } ] }); // is actually the same as: qb.setFilter({ field: "foo", operator: CondOperator.NOT_NULL }) .setFilter({ field: "baz": operator: "$eq", value: 1 }) .setOr({ field: "bar", operator: CondOperator.NOT_EQUALS, value: "test" }); qb.select(["foo", "bar"]) .setJoin({ field: "company" }) .setJoin({ field: "profile", select: ["name", "email"] }) .sortBy({ field: "bar", order: "DECS" }) .setLimit(20) .setPage(3) .resetCache() .query(); ``` -------------------------------- ### Get Single Record Source: https://github.com/nestjsx/crud/blob/master/_autodocs/endpoints.md Fetches a single record by its primary key. ```APIDOC ## GET /users/:id ### Description Fetch a single record by primary key. ### Method GET ### Endpoint /:route/:id ### Parameters #### Path Parameters - **id** (any) - Required - Primary key value #### Query Parameters - **fields** (string (CSV)) - Optional - Select specific fields - **join** (string) - Optional - Load relations ### Request Example ```http GET /users/123 Accept: application/json ``` ### Response #### Success Response (200 OK) - **id** (any) - The record's primary key - **name** (string) - The record's name - **email** (string) - The record's email - **roles** (array) - Associated roles #### Response Example ```json { "id": 123, "name": "John Doe", "email": "john@example.com", "roles": [ { "id": 1, "name": "admin" } ] } ``` #### Error Response (Not Found) - **statusCode** (number) - 404 - **message** (string) - Error message - **error** (string) - Error type ```http Status: 404 Not Found { "statusCode": 404, "message": "User not found", "error": "Not Found" } ``` ``` -------------------------------- ### Get Single User Source: https://github.com/nestjsx/crud/blob/master/_autodocs/README.md Retrieves a specific user by their unique ID. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by their unique ID. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to retrieve. ``` -------------------------------- ### RequestQueryBuilder.getOptions Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/request-query-builder.md Returns the current global options that are configured for the RequestQueryBuilder. ```APIDOC ## RequestQueryBuilder.getOptions ### Description Returns the current global options configured for the RequestQueryBuilder. ### Method `static getOptions(): RequestQueryBuilderOptions` ### Parameters None ### Request Example ```typescript const options = RequestQueryBuilder.getOptions(); console.log(options); ``` ### Response #### Success Response (200) - **options** (`RequestQueryBuilderOptions`) - The current global configuration options. ``` -------------------------------- ### Get One Resource Source: https://github.com/nestjsx/crud/wiki/Controllers Retrieves a single resource by its ID or a specific perk by its ID. ```APIDOC ## GET /heroes/:id ### Description Retrieves a single hero resource by its ID. ### Method GET ### Endpoint /heroes/:id ### Parameters #### Path Parameters - **:id** (string) - Required - The ID of the hero resource (slug). ### Response #### Success Response (200) - resource object #### Error Response (404) - error object ``` ```APIDOC ## GET /heroes/:heroId/perks/:id ### Description Retrieves a specific perk resource by its ID for a given hero. ### Method GET ### Endpoint /heroes/:heroId/perks/:id ### Parameters #### Path Parameters - **:id** (string) - Required - The ID of the perk resource (slug). ### Response #### Success Response (200) - resource object #### Error Response (404) - error object ``` -------------------------------- ### Get Many Resources Source: https://github.com/nestjsx/crud/wiki/Controllers Retrieves a collection of resources or a paginated object containing resources. ```APIDOC ## GET /heroes ### Description Retrieves a collection of resources. ### Method GET ### Endpoint /heroes ### Response #### Success Response (200) - array of resources | pagination object with data ``` ```APIDOC ## GET /heroes/:heroId/perks ### Description Retrieves a collection of perks for a specific hero. ### Method GET ### Endpoint /heroes/:heroId/perks ### Response #### Success Response (200) - array of resources | pagination object with data ``` -------------------------------- ### Create Query String with Initial Parameters Source: https://github.com/nestjsx/crud/wiki/Requests Generate a query string by passing all desired parameters directly to the RequestQueryBuilder.create method. This is an alternative to using chaining methods for query construction. ```typescript const queryString = RequestQueryBuilder.create({ fields: ["name", "email"], search: { isActive: true }, join: [{ field: "company" }], sort: [{ field: "id", order: "DESC" }], page: 1, limit: 25, resetCache: true }).query(); ``` -------------------------------- ### Get Current RequestQueryBuilder Options Source: https://github.com/nestjsx/crud/blob/master/_autodocs/api-reference/request-query-builder.md Retrieves the current global options configured for the RequestQueryBuilder. ```typescript static getOptions(): RequestQueryBuilderOptions ``` -------------------------------- ### Applying CrudAuth Decorator Source: https://github.com/nestjsx/crud/wiki/Controllers Example of applying the @CrudAuth() decorator to a controller with property and filter options. ```typescript @Crud({...}) @CrudAuth({ property: 'user', filter: (user: User) => ({ id: user.id, isActive: true, }) }) ```