=============== LIBRARY RULES =============== From library maintainers: - experimentalDecorators and emitDecoratorMetadata must be enabled in tsconfig.json - Use bindingCargo() middleware to bind request data to class instances - Validation decorators can be stacked on class properties - Supports nested objects and polymorphic binding via type decorators ### Install express-cargo dependencies Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/installation.md Install the library and reflect-metadata using your preferred package manager. ```bash npm install express-cargo reflect-metadata ``` ```bash yarn add express-cargo reflect-metadata ``` ```bash pnpm add express-cargo reflect-metadata ``` -------------------------------- ### Install Express-Cargo and Reflect Metadata Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Install the express-cargo library along with reflect-metadata, which is required for decorator functionality. ```bash npm install express-cargo reflect-metadata ``` -------------------------------- ### Install TypeScript Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Install TypeScript as a development dependency if it is not already present in your project. ```bash npm install -D typescript ``` -------------------------------- ### Usage Example: Header Mapping Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/virtual.md Example demonstrating how to map custom headers using the @Request decorator. ```APIDOC ## POST /headers ### Description Maps a custom header value from the request into a class property using the @Request decorator. ### Method POST ### Endpoint /headers ### Request Headers - **x-custom-header** (string) - Required - A custom header value. ### Request Example (No specific request body, but requires the custom header) ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **data** (object) - The mapped header data. - **customHeader** (string) - The value of the 'x-custom-header'. #### Response Example ```json { "message": "Header data mapped using @request!", "data": { "customHeader": "my-header-value" } } ``` ``` -------------------------------- ### Usage Example: Order Processing Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/virtual.md Example demonstrating the use of @Body, @Virtual, and @Request decorators for processing order data. ```APIDOC ## POST /orders ### Description Processes order data, including computed total price, using virtual fields. ### Method POST ### Endpoint /orders ### Request Body - **price** (number) - Required - The price of the item. - **quantity** (number) - Required - The quantity of the item. ### Request Example ```json { "price": 50, "quantity": 2 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **data** (object) - The processed order data including the computed total. - **price** (number) - The price of the item. - **quantity** (number) - The quantity of the item. - **total** (number) - The computed total price (price * quantity). #### Response Example ```json { "message": "Order data processed with virtual fields!", "data": { "price": 50, "quantity": 2, "total": 100 } } ``` ``` -------------------------------- ### Run the Development Server Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Start the application using the development script defined in package.json. ```shell npm run dev ``` -------------------------------- ### Verify Node.js and pnpm Installation Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Check if Node.js and pnpm are installed correctly by displaying their versions. Ensure Node.js version 18 or later is used. ```shell node -v pnpm -v ``` -------------------------------- ### Base Server with express-cargo Setup Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Set up a basic Express server and integrate express-cargo for request handling and validation using DTOs. ```typescript import express from 'express' import { bindingCargo, getCargo, Body, Query, Header, Params, Min, Max, Equal, NotEqual, Prefix, Suffix } from 'express-cargo' import errorHandlerRouter from './errorHandler' const app = express() const port = process.env.PORT || 3000 app.use(express.json()) app.use(express.urlencoded({ extended: true })) app.use(errorHandlerRouter) app.listen(port, () => {console.log(`Example app listening on port ${port}`)}) class ExampleRequest { @Body() // Extract fields from the request body @Equal('1') // If the value is not "1", a validation error occurs id!: string } app.post('/example', bindingCargo(ExampleRequest), (req, res) => { // bindingCargo(Class): Request → DTO conversion + validation const cargo = getCargo(req) // Return a validated type-safe object res.json(cargo) }) ``` -------------------------------- ### Install express and express-cargo Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Add express, express-cargo, and necessary type definitions and metadata support to your project. ```shell pnpm add express express-cargo pnpm add -D @types/express pnpm add reflect-metadata ``` -------------------------------- ### Test Request and Response Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Example of a POST request to the /example endpoint with a valid JSON body and the expected successful response. ```http POST http://localhost:3000/example Content-Type: application/json { "id": "1" } ``` ```http { "id": "1" } ``` -------------------------------- ### Install TypeScript Dependencies Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Add TypeScript and related development tools as development dependencies to your project. ```shell pnpm add -D typescript ts-node @types/node ``` -------------------------------- ### Transformed Data Output Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/transforms.md This JSON output illustrates the result of processing the example request URL. The 'sortBy' value is converted to lowercase, and the 'count' value is doubled by the @Transform decorators. ```json { "message": "Search parameters transformed successfully!", "data": { "sortBy": "title", "count": 10 }, "sortByType": "string", "countType": "number", "doubleCount": 10 } ``` -------------------------------- ### List Decorator Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the @List decorator to specify the element type for an array field. This example defines an array of strings. ```typescript @List(String) tags!: string[] ``` -------------------------------- ### Request Decorator Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the @Request decorator to extract a value directly from the Express Request object. The example retrieves the client's IP address. ```typescript @Request(req => req.ip) clientIp!: string ``` -------------------------------- ### Transform Decorator Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the @Transform decorator to apply a transformation function to a parsed value. The example shows trimming whitespace from a string. ```typescript @Transform(v => v.trim()) name!: string ``` -------------------------------- ### Virtual Decorator Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the @Virtual decorator to compute a field's value based on other fields in the object. This example concatenates first and last names. ```typescript @Virtual(obj => obj.firstName + ' ' + obj.lastName) fullName!: string ``` -------------------------------- ### Each Decorator Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the @Each decorator to apply validation rules to each individual element within an array. This example applies a length constraint to each string in the tags array. ```typescript @Each(Length(10)) tags!: string[] ``` -------------------------------- ### Nested Binding Response Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/nested-binding.md The expected JSON response structure after successful binding of a nested object. ```json { "message": "Nested bound successfully!", "data": { "profile": { "nickname": "coder123" } } } ``` -------------------------------- ### Quick Start: Express-Cargo Request Binding Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Demonstrates how to set up an Express server with express-cargo to bind request data (body, params, headers) into a class instance using decorators. Ensure express.json() middleware is used before binding. ```typescript import express from 'express' import { Body, bindingCargo, getCargo, min, Header, Params } from 'express-cargo' const app = express() app.use(express.json()) class RequestExample { @Body() name!: string @Body() @Min(0) age!: number @Params('id') id!: number @Header() authorization!: string } app.post('/:id', bindingCargo(RequestExample), (req, res) => { const data = getCargo(req) // write your code with bound data }) app.listen(3000) ``` -------------------------------- ### Default Decorator Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the @Default decorator to set a default value for a field if it is missing in the input data. This example sets a default count of 0. ```typescript @Default(0) count!: number ``` -------------------------------- ### Prefix String Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Prefix(prefixText)` to ensure a string starts with a specific prefix. The `!` indicates a non-nullable property. ```typescript @Prefix('IMG_') fileName!: string ``` -------------------------------- ### Express-Cargo Validation Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Demonstrates how to use Express-Cargo validation decorators within an Express application. It shows defining a request class with validation rules, applying the bindingCargo middleware, accessing validated data, and implementing error handling for validation failures. ```typescript import express, { Request, Response, NextFunction } from 'express' import { bindingCargo, getCargo, Body, Min, Max, Suffix, CargoValidationError } from 'express-cargo' // 1. Define a class with source and validation rules class CreateAssetRequest { @Body('name') assetName!: string @Body('type') @Suffix('.png') assetType!: string @Body('quantity') @Min(1) @Max(100) quantity!: number } const app = express() app.use(express.json()) // 2. Apply the bindingCargo middleware to a route app.post('/assets', bindingCargo(CreateAssetRequest), (req: Request, res: Response) => { // 3. If validation succeeds, access the data using getCargo const assetData = getCargo(req) res.json({ message: 'Asset created successfully!', data: assetData, }) }) // 4. Add an error handling middleware to catch validation errors app.use((err: Error, req: Request, res: Response, next: NextFunction) => { if (err instanceof CargoValidationError) { res.status(400).json({ message: 'Validation Failed', errors: err.errors.map(e => e.message), }) } else { next(err) } }) /* To test this endpoint, send a POST request to /assets. Example of a VALID request body: { "name": "My-Asset", "type": "icon.png", "quantity": 10 } Example of an INVALID request body: { "name": "My-Asset", "type": "icon.jpg", // Fails @Suffix('.png') "quantity": 101 // Fails @Max(100) } */ ``` -------------------------------- ### Test Request with Validation Error Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Example of a POST request to the /example endpoint with an invalid JSON body that triggers a validation error. ```http POST http://localhost:3000/example Content-Type: application/json { "id": "2" } ``` -------------------------------- ### Type Decorator Example Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the @Type decorator to specify the class for transforming raw data, supporting dynamic resolution and circular dependencies. ```typescript @Type(() => User) user!: User ``` -------------------------------- ### Example JSON Error Response Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Illustrates the structure of a JSON error response when validation fails in Express-Cargo. It includes a general message and a detailed array of specific field errors. ```json { "message": "Validation Failed", "errors": [ "type: assetType must end with .png", "quantity: quantity must be <= 100" ] } ``` -------------------------------- ### Transform Incoming Request Data with @Transform Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/transforms.md Use the @Transform decorator to normalize and process request data into a desired format. This ensures consistent API processing of diverse user inputs, improving application stability. The example demonstrates transforming a 'sortBy' string to lowercase and doubling a 'count' number. ```typescript import express, { Request, Response } from 'express' import { bindingCargo, getCargo, Query, Transform } from 'express-cargo' // 1. Define a class with data processing and normalization rules class SearchRequest { // Transforms the 'sortBy' query parameter to lowercase for consistent sorting @Query() @Transform((value: string) => value.toLowerCase()) sortBy!: string // Doubles the 'count' query parameter value @Query() @Transform((value: number) => value * 2) count!: number } const app = express() app.use(express.json()) // 2. Apply the bindingCargo middleware to the route app.get('/search', bindingCargo(SearchRequest), (req: Request, res: Response) => { // 3. Access the transformed data with the correct types const searchParams = getCargo(req) res.json({ message: 'Search parameters transformed successfully!', data: searchParams, // Verify the type of the transformed data sortByType: typeof searchParams.sortBy, countType: typeof searchParams.count, doubleCount: searchParams.count, }) }) /* To test this endpoint, send a GET request to /search. Example request URL: http://localhost:3000/search?sortBy=TITLE&count=10 */ ``` -------------------------------- ### Create New Project with pnpm Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Initialize a new project directory and set up the project using pnpm. ```shell mkdir express-cargo-example cd express-cargo-example pnpm init ``` -------------------------------- ### Initialize TypeScript Configuration Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Generate a tsconfig.json file for your TypeScript project. ```shell pnpm tsc --init ``` -------------------------------- ### Recommended tsconfig.json Settings Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/getting-started.md Configure tsconfig.json to enable experimental decorators and emit decorator metadata, which are required for express-cargo. ```json { "compilerOptions": { ..., "experimentalDecorators": true, // express-cargo required "emitDecoratorMetadata": true, // use type metadata ... }, ... } ``` -------------------------------- ### Define Virtual and Request-Derived Fields Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/virtual.md Demonstrates defining classes with @Virtual and @Request decorators and binding them to Express routes using bindingCargo. ```typescript import express from 'express' import { Body, Virtual, Request, bindingCargo, getCargo } from 'express-cargo' // 1. Define Object with virtual and request-derived fields class OrderExample { @Body('price') price!: number @Body('quantity') quantity!: number // Computed field not present in the request @Virtual((obj: OrderExample) => obj.price * obj.quantity) total!: number } class HeaderExample { // Field derived directly from the request object @Request(req => req.headers['x-custom-header'] as string) customHeader!: string } // 2. Setup Express app and route const app = express() app.use(express.json()) app.post('/orders', bindingCargo(OrderExample), (req, res) => { const orderData = getCargo(req) res.json({ message: 'Order data processed with virtual fields!', data: orderData }) }) app.post('/headers', bindingCargo(HeaderExample), (req, res) => { const headerData = getCargo(req) res.json({ message: 'Header data mapped using @request!', data: headerData }) }) ``` -------------------------------- ### Inheriting Field Decorators with TypeScript Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/inherited-binding.md Demonstrates how to define a base class with decorated fields and extend it in a child class. Ensure decorators are correctly applied to fields in both parent and child classes for inheritance to work. ```typescript class BaseRequest { @Body() @Length(10) id!: string } class CreateUserRequest extends BaseRequest { @Body() @OneOf(["admin", "user"]) role!: string } ``` -------------------------------- ### Configure tsconfig.json for decorators Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/installation.md Enable experimental decorators and decorator metadata in your TypeScript configuration. ```json { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } } ``` -------------------------------- ### Email Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Validates that the decorated property holds a correctly formatted email address. ```APIDOC ## @Email() ### Description Validates that the decorated property is a valid email address. ``` -------------------------------- ### Regexp Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Ensures that a field's value matches a provided regular expression pattern. Useful for format validation like emails or phone numbers. ```APIDOC ## @Regexp(pattern: RegExp, message?: string) ### Description Validates that the decorated field matches the specified regular expression pattern. This decorator is useful for enforcing format rules such as email, phone numbers, etc. ### Parameters - **`pattern`**: A RegExp object used to test the field value. The value is valid if it matches the pattern. - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Define UserInfoRequest with Body and Header Mapping Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/examples/nested-request.md Maps user details from the request body and extracts an authorization token from headers. Uses @Transform to clean the token value. ```typescript // user.request.ts import { Body, Header, Optional, Prefix, Transform } from 'express-cargo' export class UserInfoRequest { @Body('name') name!: string @Body('email') @Prefix('user-') email!: string @Body('age') @Optional() age?: number // Extract the token from the Authorization header. @Header('authorization') @Transform((value: string) => { if (value.startsWith('Bearer ')) { return value.substring(7); } return '' }) authorization!: string } ``` -------------------------------- ### Extract Request Data with Decorators Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/source-decorators.md Use decorators to bind data from the request body, query parameters, headers, or URL parameters to a DTO. Ensure necessary middleware (like session) is configured if using @Session(). ```typescript class Request { @Body('email') email!: string @Query('limit') limit!: number @Header('Authorization') authorization!: string } ``` -------------------------------- ### IsUrl Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Validates that the decorated field is a valid URL. By default, it allows 'http', 'https', and 'ftp' protocols. You can specify custom allowed protocols. ```APIDOC ## @IsUrl(options?: IsUrlOptions, message?: string) ### Description Validates that the decorated field is a valid URL. By default, `http`, `https`, and `ftp` protocols are allowed. ### Parameters - **`options`** (optional): - **`protocols`**: An array of allowed protocols. Defaults to `['http', 'https', 'ftp']`. - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Minimum Length Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@MinLength(min)` to ensure a string's length is at least a specified minimum. The `!` indicates a non-nullable property. ```typescript @MinLength(8) password!: string ``` -------------------------------- ### Limit Minimum Array Size Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@ListMinSize` to enforce a lower limit on the number of elements in an array. This ensures a minimum level of input detail. ```typescript tags!: string[] @ListMinSize(5) ``` -------------------------------- ### Using @List Decorator for Array Binding Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/list-decorator.md Demonstrates how to use the @List decorator to bind and cast various array types (String, Number, Boolean, Date, CustomClass) from request bodies in an Express.js route. Requires importing necessary modules from 'express-cargo'. ```typescript import express, { Router } from 'express' import { Body, List, bindingCargo, getCargo } from 'express-cargo' const router: Router = express.Router() // 1. Define a custom class (optional) class CustomClass { @Body() name!: string @Body() age!: number } // 2. Define the class with array fields class ListSample { @Body() @List(String) stringArray!: string[] @Body() @List(Number) numberArray!: number[] @Body() @List(Boolean) booleanArray!: boolean[] @Body() @List(Date) dateArray!: Date[] @Body() @List('string') stringLiteralArray!: string[] @Body() @List(CustomClass) customClassArray!: CustomClass[] } // 3. Setup Express route router.post('/list', bindingCargo(ListSample), (req, res) => { const cargo = getCargo(req) res.json(cargo) }) export default router ``` -------------------------------- ### Output of getCargo with @List Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/list-decorator.md Illustrates the structure and type casting of the object returned by `getCargo(req)` after processing an array-based request body. Note that Date strings are converted to Date objects and custom class arrays are instantiated. ```typescript // Object returned by getCargo(req): const cargo = { stringArray: ["apple", "banana"], numberArray: [1, 2, 3], booleanArray: [true, false], dateArray: [ // These are actual Date objects new Date("2024-01-01T00:00:00.000Z"), new Date("2024-01-02T00:00:00.000Z") ], stringLiteralArray: ["one", "two"], customClassArray: [ // These are instances of CustomClass { name: "John", age: 30 }, { name: "Jane", age: 25 } ] }; ``` -------------------------------- ### Define and Bind Nested Objects Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/nested-binding.md Use the @Body decorator to map nested properties to class instances and apply the bindingCargo middleware to routes. ```typescript import express, { Request, Response } from 'express' import { Body, bindingCargo, getCargo } from 'express-cargo' // 1. Define nested Object class Profile { @Body('nickname') nickname!: string } class ExampleObject { @Body('profile') profile!: Profile } // 2. Setup Express app and route const app = express() app.use(express.json()) app.post('/submit', bindingCargo(ExampleObject), (req: Request, res: Response) => { const requestData = getCargo(req) res.json({ message: 'Nested bound successfully!', data: requestData, }) }) ``` -------------------------------- ### MinDate Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Ensures the decorated field's date is on or after a specified minimum date. The minimum date can be a fixed Date object or a function returning a Date. ```APIDOC ## @MinDate(min: Date | (() => Date), message?: string) ### Description Validates that the decorated field is a `Date` that is on or after the given minimum date. Accepts a fixed `Date` or a function that returns a `Date` for dynamic comparison. ### Parameters - **`min`**: The minimum allowed date, or a function that returns it. - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### IsHexColor Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Checks if the decorated field is a valid hex color code. Supports formats like #RGB, #RGBA, #RRGGBB, and #RRGGBBAA (case-insensitive), requiring the '#' prefix. ```APIDOC ## @IsHexColor(message?: string) ### Description Validates that the decorated field is a valid hex color code. Supports `#RGB`, `#RGBA`, `#RRGGBB`, and `#RRGGBBAA` formats (case-insensitive). The `#` prefix is required. ### Parameters - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Maximum Length Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@MaxLength(max)` to ensure a string's length is at most a specified maximum. The `!` indicates a non-nullable property. ```typescript @MaxLength(20) username!: string ``` -------------------------------- ### Define OrderRequest with Nested UserInfoRequest Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/examples/nested-request.md Represents an order request, including a nested UserInfoRequest object. Uses @Min and @Max decorators for quantity validation. ```typescript // order.request.ts import { Body, Min, Max } from 'express-cargo' import { UserInfoRequest } from './user.request' export class OrderRequest { @Body('productId') productId!: string @Body('quantity') @Min(1) @Max(10) quantity!: number @Body('user') user!: UserInfoRequest } ``` -------------------------------- ### Built-in Decorators Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/source-decorators.md Express Cargo provides several built-in decorators to extract data from different parts of the HTTP request. ```APIDOC ## Built-in Decorators Express Cargo offers a set of decorators to simplify the process of accessing request data. ### `@Body()` - **Description**: Extracts data from the HTTP request body. - **Source**: `req.body` ### `@Query()` - **Description**: Extracts data from the HTTP request query parameters. - **Source**: `req.query` ### `@Header()` - **Description**: Extracts values from the HTTP request headers. Useful for accessing metadata like authentication tokens. - **Source**: `req.headers` ### `@Uri()` / `@Params()` - **Description**: Extracts path variables from the HTTP request URL. Both decorators are aliases and perform the same function, typically used for resource identifiers. - **Source**: `req.params` - **Common Usage**: Routes like `/users/:id`, `/posts/:postId` ### `@Session()` - **Description**: Extracts values stored in the session. Useful for server-side state like authenticated user information. Requires session middleware to be configured. - **Source**: `req.session` ### Usage Example ```typescript class Request { @Body('email') email!: string @Query('limit') limit!: number @Header('Authorization') authorization!: string } ``` ``` -------------------------------- ### Range Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Range(min, max)` to ensure a number is between a minimum and maximum value, inclusive. The `!` indicates a non-nullable property. ```typescript @Range(1, 5) rating!: number ``` -------------------------------- ### IsUppercase Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Checks if all characters in the decorated field are uppercase. An optional custom error message can be provided. ```APIDOC ## @IsUppercase(message?: string) ### Description Validates that the decorated field contains only uppercase characters. ### Parameters - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Validate URL Format Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the `@IsUrl` decorator to validate if a field represents a valid URL. By default, it allows `http`, `https`, and `ftp` protocols. Custom protocols can be configured via `options.protocols`. ```typescript @IsUrl() website!: string ``` -------------------------------- ### Minimum Value Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Min(minimum)` to ensure a number is greater than or equal to a specified minimum value. The `!` indicates a non-nullable property. ```typescript @Min(18) age!: number ``` -------------------------------- ### Validate Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Allows validation of a field using a custom function. You can provide a specific error message or use a default one. ```APIDOC ## @Validate(validateFn: (value: unknown) => boolean, message?: string) ### Description Validates a value using a custom validation function. This decorator provides flexibility to implement validation logic beyond the built-in ones. ### Parameters - **`validateFn`**: A function that receives the field value and returns true if valid, false otherwise. - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### IsHexadecimal Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Validates that the decorated field represents a hexadecimal number. It accepts characters 0-9 and a-f (case-insensitive) and optionally allows the '0x' prefix. ```APIDOC ## @IsHexadecimal(message?: string) ### Description Validates that the decorated field is a hexadecimal number. The value must contain only characters `0-9` and `a-f` (case-insensitive). The `0x` prefix is also allowed. ### Parameters - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Check for Non-Equality Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@NotEqual` to ensure a value is not equal to a specified value. This is useful for preventing default or reserved values. ```typescript role!: string @NotEqual('admin') ``` -------------------------------- ### Limit Maximum Array Size Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@ListMaxSize` to enforce an upper limit on the number of elements in an array. This is useful for controlling resource usage or input complexity. ```typescript tags!: string[] @ListMaxSize(5) ``` -------------------------------- ### Equality Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Equal(value)` to check if a value is strictly equal to a specified value. The `!` indicates a non-nullable property. ```typescript @Equal('production') env!: string ``` -------------------------------- ### IsLowercase Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Validates that the decorated field contains only lowercase characters. A custom error message can be specified. ```APIDOC ## @IsLowercase(message?: string) ### Description Validates that the decorated field contains only lowercase characters. ### Parameters - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Exact Length Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Length(value)` to enforce that a string has an exact length. The `!` indicates a non-nullable property. ```typescript @Length(6) otp!: string ``` -------------------------------- ### IsJwt Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Validates that the decorated field adheres to the JWT format (header.payload.signature). It checks the format using Base64URL characters but does not verify the signature or token validity. ```APIDOC ## @IsJwt(message?: string) ### Description Validates that the decorated field follows the JWT format (`header.payload.signature`). Each part must consist of Base64URL characters (A-Z, a-z, 0-9, `-`, `_`). This decorator only checks the format — it does not verify the signature or token validity. ### Parameters - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Validate Minimum Date Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md The `@MinDate` decorator validates that a `Date` field is on or after a specified minimum date. The minimum date can be a fixed `Date` object or a function returning a `Date`. ```typescript @MinDate(new Date('2000-01-01')) createdAt!: Date ``` -------------------------------- ### Validate String Against Regular Expression Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Regexp` to validate that a string matches a given regular expression pattern. This is useful for formats like phone numbers or specific ID structures. ```typescript phone!: string @Regexp(/^[0-9]+$/, 'digits only') ``` -------------------------------- ### Alpha Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Checks if the decorated field contains only alphabetic characters (a-z, A-Z). An optional custom error message can be provided. ```APIDOC ## @Alpha(message?: string) ### Description Validates that the decorated field contains alphabetic characters only (uppercase or lowercase English letters, A–Z / a–z). ### Parameters - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Use bindingCargo Middleware in Express Route Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/examples/nested-request.md Applies the bindingCargo middleware to an Express route to handle nested request binding. Retrieves the bound OrderRequest object using getCargo. ```typescript router.post('/orders', bindingCargo(OrderRequest), (req, res) => { const order = getCargo(req) if (order) { console.log(`Processing order for product: ${order.productId}`) console.log(`User name: ${order.user.name}`) console.log(`Auth token: ${order.user.authorization}`) // You can now use the auth token for validation or other logic. res.json({ message: 'Order received', order }) } }) ``` -------------------------------- ### MaxDate Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Validates that the decorated field's date is on or before a specified maximum date. The maximum date can be a fixed Date object or a function returning a Date. ```APIDOC ## @MaxDate(max: Date | (() => Date), message?: string) ### Description Validates that the decorated field is a `Date` that is on or before the given maximum date. Accepts a fixed `Date` or a function that returns a `Date` for dynamic comparison. ### Parameters - **`max`**: The maximum allowed date, or a function that returns it. - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Dynamic Type Resolution with Functional Resolver Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/type-and-polymorphism.md Pass a function to @Type that inspects incoming data to return the appropriate class at runtime. This is useful for handling inheritance and polymorphism. ```typescript class Example { @Type((data) => { if (data.type === 'video') return Video; if (data.type === 'image') return Image; return DefaultMedia; }) featuredMedia!: Video | Image | DefaultMedia; } ``` -------------------------------- ### Transform Stringified Array to String Array Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/custom-transformer.md Use the `@Query` decorator with a string array type to automatically transform a comma-separated query parameter into a string array. Ensure the query parameter is provided in the format 'tag1,tag2'. ```typescript class Request { @Query('tags') tags!: string[]; // Will cast from "tag1,tag2" to ['tag1', 'tag2'] } ``` -------------------------------- ### Alphanumeric Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Ensures the decorated field contains only alphanumeric characters (a-z, A-Z, 0-9). A custom error message can be specified. ```APIDOC ## @Alphanumeric(message?: string) ### Description Validates that the decorated field contains alphanumeric characters only (English letters and digits, A–Z, a–z, 0–9). ### Parameters - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Contains String Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Contains(seed)` to validate that a string includes a specific substring. The `!` indicates a non-nullable property. ```typescript @Contains('hello') greeting!: string ``` -------------------------------- ### Validate Email Format Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Email` to automatically validate that a string conforms to a standard email address format. This is a common requirement for user input. ```typescript email!: string @Email() ``` -------------------------------- ### Maximum Value Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Max(maximum)` to ensure a number is less than or equal to a specified maximum value. The `!` indicates a non-nullable property. ```typescript @Max(100) score!: number ``` -------------------------------- ### Uuid Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/validators.md Validates that the decorated field is a valid UUID. Optionally, you can specify a particular UUID version (v1, v3, v4, or v5) for validation. ```APIDOC ## @Uuid(version?: 'v1' | 'v3' | 'v4' | 'v5', message?: string) ### Description Validates that the decorated field is a valid UUID string, optionally restricted to a specific version (v1, v3, v4, or v5). ### Parameters - **`version`** (optional): The specific UUID version to validate against. If omitted, it validates against v1, v3, v4, or v5. - **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used. ``` -------------------------------- ### Validate Field Dependency (With) Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md The `@With` decorator enforces a dependency: if the decorated field has a value, the field specified by `fieldName` must also have a value. ```typescript @With('price') discountRate?: number ``` -------------------------------- ### Suffix String Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Suffix(suffixText)` to ensure a string ends with a specific suffix. The `!` indicates a non-nullable property. ```typescript @Suffix('.jpg') fileName!: string ``` -------------------------------- ### Dynamic Type Resolution with Structural Discriminator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/type-and-polymorphism.md Utilize the `discriminator` option within @Type for a declarative approach to map specific property values to their respective classes, simplifying polymorphic data handling. ```typescript class Example { @Type(() => Media, { discriminator: { property: 'kind', subTypes: [ { name: 'v', value: Video }, { name: 'i', value: Image }, ], }, }) gallery!: (Video | Image)[]; } ``` -------------------------------- ### Check for False Value Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@IsFalse` to validate that a boolean field is strictly `false`. This can be used for fields indicating a disabled or blocked state. ```typescript blocked!: boolean @IsFalse() ``` -------------------------------- ### Check for True Value Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@IsTrue` to validate that a boolean field is strictly `true`. This is commonly used for agreement checkboxes. ```typescript acceptedTerms!: boolean @IsTrue() ``` -------------------------------- ### Validate Field Exclusivity (Without) Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the `@Without` decorator to ensure mutual exclusivity: if the decorated field has a value, the field specified by `fieldName` must NOT have a value. ```typescript @Without('isGuest') password?: string ``` -------------------------------- ### Validate Hexadecimal Color Code Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md The `@IsHexColor` decorator validates if a field is a valid hexadecimal color code. It supports `#RGB`, `#RGBA`, `#RRGGBB`, and `#RRGGBBAA` formats, case-insensitively. The '#' prefix is mandatory. ```typescript @IsHexColor() color!: string ``` -------------------------------- ### Validate UUID Format Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Uuid` to validate that a string is a valid Universally Unique Identifier (UUID). Optionally specify the UUID version (v1, v3, v4, or v5) for stricter validation. ```typescript requestId!: string @Uuid('v4') ``` -------------------------------- ### Resolving Circular Dependencies with Thunked @Type Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/type-and-polymorphism.md Employ a Thunk (arrow function) with @Type to defer class resolution when classes reference each other, preventing ReferenceErrors due to undefined classes during initialization. ```typescript class Post { @Body() title!: string; @Body() @Type(() => User) // Resolved lazily to avoid "User is not defined" error author!: User; } class User { @Body() name!: string; /** * @Type automatically detects the array type via metadata. * No explicit @List(Post) decorator is required. */ @Body() @Type(() => Post) posts!: Post[]; } ``` -------------------------------- ### Basic Nested Mapping with @Type Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/type-and-polymorphism.md Use @Type to specify the target class for a property that should be an instance of another class. This ensures proper transformation of nested JSON objects into class instances. ```typescript import { Body, Type } from 'express-cargo'; class Profile { @Body() bio!: string; } class User { @Body() name!: string; @Body() @Type(() => Profile) // Automatically transforms into a Profile instance profile!: Profile; } ``` -------------------------------- ### Request-Derived Field Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/virtual.md The @Request decorator maps a value from the Express Request object into a class property. ```APIDOC ## @Request(transformer: (req: Request) => T) ### Description Maps a value from the Express `Request` object into a class property. ### Parameters #### Transformer Function - **transformer** (function) - Required - A function that receives the Request object and returns the value to bind. ``` -------------------------------- ### Optional Value Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Optional()` to skip validation when a value is null or undefined. This is useful for fields that are not always required. ```typescript @Optional() value?: number ``` -------------------------------- ### Validate Maximum Date Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@MaxDate` to validate that a `Date` field is on or before a specified maximum date. The maximum date can be a fixed `Date` object or a function returning a `Date`. ```typescript @MaxDate(new Date('2099-12-31')) createdAt!: Date ``` -------------------------------- ### Check if Value is One of Several Options Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@OneOf` to restrict a field's value to a predefined set of options. Ensure the options are provided as a readonly array. ```typescript method!: 'credit' | 'debit' @OneOf(['credit','debit'] as const) ``` -------------------------------- ### Apply @Default decorator to a class property Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/advanced/default.md Use the @Default decorator on a class property to ensure it receives a fallback value when missing from the request body. ```typescript class Request { @Body() @Default(1) price!: number; } ``` -------------------------------- ### Custom Cargo Error Handler Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Implement a custom error handler for Express-Cargo to manage validation errors specifically. This handler returns a 400 status with detailed validation messages. ```typescript import { setCargoErrorHandler, CargoValidationError } from 'express-cargo' // Custom error handler setCargoErrorHandler((err, req, res, next) => { if (err instanceof CargoValidationError) { res.status(400).json({ error: 'Validation failed', details: err.errors.map(e => ({ field: e.field, message: e.name })) }) } else { next(err) } }) ``` -------------------------------- ### Validate JSON Web Token (JWT) Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md The `@IsJwt` decorator validates if a field's value is a correctly formatted JSON Web Token (JWT) in the `header.payload.signature` structure. ```typescript @IsJwt() accessToken!: string ``` -------------------------------- ### Custom Validation Function Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Validate` with a custom validation function for complex or business-specific validation logic. The function receives the value and should return `true` if valid. ```typescript email!: string @Validate(v => typeof v === 'string' && v.includes('@'), 'invalid email') ``` -------------------------------- ### Validate Uppercase Characters Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md The `@IsUppercase` decorator checks if a field's value consists solely of uppercase characters. An optional message can be specified. ```typescript @IsUppercase() countryCode!: string ``` -------------------------------- ### Virtual Field Decorator Source: https://github.com/beyond-imagination/express-cargo/blob/main/apps/docs/docs/decorators/virtual.md The @Virtual decorator defines a computed property whose value is derived from other properties of the object. ```APIDOC ## @Virtual(transformer: (obj: object) => T) ### Description Defines a computed property that is not directly sourced from the request. Its value is derived from other properties of the object. ### Parameters #### Transformer Function - **transformer** (function) - Required - A function that receives the object instance and returns the computed value. ``` -------------------------------- ### Check if Array Contains Specific Values Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@ListContains` to ensure an array includes all specified values. A custom comparator can be provided for complex comparisons. ```typescript nums!: number[] @ListContains([1, 2]) ``` ```typescript strs!: string[] @ListContains(['a'], (e, a) => a.toLowerCase() === e) ``` -------------------------------- ### Validate Alphabetic Characters Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the `@Alpha` decorator to ensure a field contains only alphabetic characters (A-Z, a-z). An optional custom message can be provided. ```typescript @Alpha() firstName!: string ``` -------------------------------- ### Validate Against Enum Members Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@Enum` to ensure a field's value is a valid member of a provided enum object. This enforces type safety and restricts values to predefined sets. ```typescript role!: UserRole @Enum(UserRole) ``` -------------------------------- ### Validate Lowercase Characters Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@IsLowercase` to validate that a field contains only lowercase characters. A custom error message is optional. ```typescript @IsLowercase() username!: string ``` -------------------------------- ### Validate Hexadecimal String Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@IsHexadecimal` to validate if a field contains a hexadecimal number. It accepts characters `0-9` and `a-f` (case-insensitive) and optionally the `0x` prefix. ```typescript @IsHexadecimal() color!: string ``` -------------------------------- ### Check if Array Does Not Contain Specific Values Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use `@ListNotContains` to ensure an array does not include any of the specified values. A custom comparator can be provided for complex comparisons. ```typescript nums!: number[] @ListNotContains([1, 2]) ``` ```typescript strs!: string[] @ListNotContains(['a'], (e, a) => a.toLowerCase() === e) ``` -------------------------------- ### Validate Alphanumeric Characters Source: https://github.com/beyond-imagination/express-cargo/blob/main/README.md Use the `@Alphanumeric` decorator to validate that a field contains only alphanumeric characters (A-Z, a-z, 0-9). A custom message is optional. ```typescript @Alphanumeric() productCode!: string ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.