### Install Dependencies for Benchmarking Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/validation-comparison/README.md This command installs the necessary Node.js dependencies for running the validation benchmarks. It assumes you are in the 'benchmarks' directory of the project. ```bash cd benchmarks npm install ``` -------------------------------- ### Install Dependencies and Build Project with npm Source: https://github.com/isqanderm/data-mapper/blob/main/CONTRIBUTING.md Commands to install project dependencies using npm and build the project. These are essential steps for setting up the development environment. ```bash npm install npm run build ``` -------------------------------- ### Clone and Setup om-data-mapper Repository Source: https://github.com/isqanderm/data-mapper/blob/main/CONTRIBUTING.md Instructions for forking the repository, cloning it locally, and adding the upstream remote for keeping your fork updated. ```bash git clone https://github.com/YOUR_USERNAME/data-mapper.git cd data-mapper git remote add upstream https://github.com/Isqanderm/data-mapper.git ``` -------------------------------- ### E-commerce Product Mapping Example Source: https://github.com/isqanderm/data-mapper/blob/main/docs-ru/transformer-usage.md An advanced example demonstrating how to map complex e-commerce product data, including transformations like converting strings to uppercase, calculating final prices, and joining tags into a single string. ```typescript type ProductSource = { id: string; name: string; price: number; discount?: number; category: { id: string; name: string; }; tags: string[]; }; type ProductDTO = { id: string; name: string; finalPrice: number; categoryName: string; tagsString: string; isOnSale: boolean; }; @Mapper() class ProductMapper { @Map('id') id!: string; @Map('name') @Transform((v: string) => v.toUpperCase()) name!: string; @MapFrom((src: ProductSource) => { const discount = src.discount || 0; return src.price * (1 - discount / 100); }) finalPrice!: number; @Map('category.name') categoryName!: string; @Map('tags') @Transform((tags: string[]) => tags.join(', ')) tagsString!: string; @MapFrom((src: ProductSource) => (src.discount || 0) > 0) isOnSale!: boolean; } const product = { id: '123', name: 'laptop', price: 1000, discount: 10, category: { id: 'cat1', name: 'Electronics' }, tags: ['new', 'featured'] }; const dto = plainToInstance(ProductMapper, product); // { // id: '123', // name: 'LAPTOP', // finalPrice: 900, // categoryName: 'Electronics', // tagsString: 'new, featured', // isOnSale: true // } ``` -------------------------------- ### E-commerce Product Mapping Example Source: https://github.com/isqanderm/data-mapper/blob/main/docs/transformer-usage.md This example demonstrates advanced mapping for an e-commerce product. It uses decorators like @Map, @Transform, and @MapFrom to handle complex transformations, including string manipulation, conditional calculations, and nested property mapping. ```typescript type ProductSource = { id: string; name: string; price: number; discount?: number; category: { id: string; name: string; }; tags: string[]; }; type ProductDTO = { id: string; name: string; finalPrice: number; categoryName: string; tagsString: string; isOnSale: boolean; }; @Mapper() class ProductMapper { @Map('id') id!: string; @Map('name') @Transform((v: string) => v.toUpperCase()) name!: string; @MapFrom((src: ProductSource) => { const discount = src.discount || 0; return src.price * (1 - discount / 100); }) finalPrice!: number; @Map('category.name') categoryName!: string; @Map('tags') @Transform((tags: string[]) => tags.join(', ')) tagsString!: string; @MapFrom((src: ProductSource) => (src.discount || 0) > 0) isOnSale!: boolean; } const product = { id: '123', name: 'laptop', price: 1000, discount: 10, category: { id: 'cat1', name: 'Electronics' }, tags: ['new', 'featured'] }; const dto = plainToInstance(ProductMapper, product); // { // id: '123', // name: 'LAPTOP', // finalPrice: 900, // categoryName: 'Electronics', // tagsString: 'new, featured', // isOnSale: true // } ``` -------------------------------- ### Example Usage of Validation Options (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md An example showing how to apply `ValidatorOptions` when calling the `validate` function, customizing the validation behavior. ```typescript const errors = await validate(user, { skipMissingProperties: true, groups: ['create'], stopAtFirstError: true }); ``` -------------------------------- ### Install class-validator Dependency Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/validation-comparison/README.md This bash command installs the `class-validator` library using npm. This package is a peer dependency often used with data mapping and validation libraries. Ensure Node.js and npm are installed and accessible in your environment. ```bash npm install class-validator ``` -------------------------------- ### Install om-data-mapper with npm, pnpm, or yarn Source: https://github.com/isqanderm/data-mapper/blob/main/docs-ru/transformer-usage.md This snippet shows how to install the om-data-mapper package using different package managers. No additional dependencies like reflect-metadata are required. ```bash npm install om-data-mapper # or pnpm add om-data-mapper # or yarn add om-data-mapper ``` -------------------------------- ### Benchmark Output Format Example Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md Illustrates the typical output format of a benchmark run, showing operations per second and margin of error for different test cases. ```text Mapper#execute x 945,768,114 ops/sec ±1.02% (100 runs sampled) Vanilla mapper x 977,313,179 ops/sec ±2.51% (96 runs sampled) ``` -------------------------------- ### Node.js ESM Import Syntax Examples Source: https://github.com/isqanderm/data-mapper/blob/main/test/ESM_TESTING.md Demonstrates the correct and incorrect ways to import modules in Node.js ESM environments, highlighting the requirement for explicit file extensions and directory index files. These examples are crucial for understanding Node.js ESM's strict import resolution rules. ```javascript // ❌ Breaks in Node.js ESM import { Mapper } from './core/Mapper' // ✅ Works in Node.js ESM import { Mapper } from './core/Mapper.js' ``` ```javascript // ❌ Breaks in Node.js ESM import { Map } from './decorators' // ✅ Works in Node.js ESM import { Map } from './decorators/index.js' ``` -------------------------------- ### Install om-data-mapper package Source: https://github.com/isqanderm/data-mapper/blob/main/README.md This command installs the om-data-mapper package using npm. It's the first step to integrate the library into your project. ```bash npm install om-data-mapper ``` -------------------------------- ### Install om-data-mapper using npm, yarn, or pnpm Source: https://github.com/isqanderm/data-mapper/blob/main/README.md This snippet shows how to install the om-data-mapper library using different package managers. It's a prerequisite for using the library in your project. ```bash npm install om-data-mapper ``` ```bash yarn add om-data-mapper ``` ```bash pnpm add om-data-mapper ``` -------------------------------- ### Example Benchmark Output Format Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/core/README.md Illustrates the typical output format for core benchmarks, showing execution times and performance metrics for different mapping strategies. ```text ✓ core/simple.bench.ts (4) 2345ms ✓ Simple Mapping Benchmark (2) 2344ms name hz min max mean p75 p99 p995 p999 rme samples · OmDataMapper - Simple mapping 30,123,456 0.0001 0.0002 0.0001 0.0001 0.0002 0.0002 0.0002 ±0.5% 100000 · Vanilla - Simple mapping 28,456,789 0.0001 0.0002 0.0001 0.0001 0.0002 0.0002 0.0002 ±0.6% 100000 ``` -------------------------------- ### Install om-data-mapper v4.1.0 Source: https://github.com/isqanderm/data-mapper/blob/main/RELEASE_NOTES_v4.1.0.md Instructions for installing or updating the om-data-mapper package to version 4.1.0 using npm. This includes both direct installation and updating the package.json dependency. ```bash npm install om-data-mapper@4.1.0 ``` ```json { "dependencies": { "om-data-mapper": "^4.1.0" } } ``` -------------------------------- ### Migration from class-validator Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Provides instructions on how to migrate existing projects from `class-validator` to `om-data-mapper/class-validator-compat` with minimal code changes. ```APIDOC ## Migration from class-validator ### Description The Data Mapper validation module is designed to be 100% API compatible with `class-validator`. This allows for a seamless migration by simply changing the import path, offering significant performance improvements without altering your existing validation logic. ### Method **Not Applicable** (This describes a concept, not an endpoint) ### Endpoint **Not Applicable** ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **Not Applicable** ### Request Example ```typescript // Before import { validate, IsString } from 'class-validator'; // After import { validate, IsString } from 'om-data-mapper/class-validator-compat'; // No other changes needed! Your existing code will work with 10x better performance. ``` ### Response #### Success Response (200) **Not Applicable** #### Response Example **Not Applicable** ``` -------------------------------- ### Quick Start: Migrate class-transformer import to om-data-mapper compatibility layer Source: https://github.com/isqanderm/data-mapper/blob/main/docs/migration-class-transformer.md Demonstrates the simplest migration step: changing the import path for class-transformer compatible functions from 'class-transformer' to 'om-data-mapper/class-transformer-compat'. This allows existing code to work with the new library with performance gains. ```typescript import { plainToClass, Expose, Type } from 'om-data-mapper/class-transformer-compat'; ``` -------------------------------- ### Decorator API vs. Compatibility API Usage (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/transformer-usage.md Presents two approaches for using om-data-mapper: the new Decorator API for new projects and the Compatibility API for migrating from class-transformer. The example demonstrates a basic DTO structure for both scenarios. ```typescript // ✅ New projects: Use Decorator API @Mapper() class UserMapper { ... } // ✅ Migrating from class-transformer: Use Compatibility API class UserDTO { @Expose() name: string; } ``` -------------------------------- ### Mapper Instance Reuse Best Practice (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/transformer-usage.md Highlights the importance of reusing mapper instances for better performance. The example contrasts the recommended approach of creating a mapper once and reusing it with the inefficient practice of creating a new mapper for each transformation. ```typescript // ✅ Good: Reuse mapper const mapper = createMapper(UserMapper); const result1 = mapper.transform(source1); const result2 = mapper.transform(source2); // ❌ Bad: Create new mapper each time const result1 = plainToInstance(UserMapper, source1); const result2 = plainToInstance(UserMapper, source2); ``` -------------------------------- ### Run Core Benchmarks with Vitest Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md This command executes a specific core benchmark file using Vitest. Ensure you have Vitest installed and the command is run from the project root or appropriate directory. ```bash npx vitest bench core/your-file.bench.ts ``` -------------------------------- ### Benchmark JSON Output Example Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md Provides an example of the JSON output generated by benchmarks, suitable for programmatic analysis. It includes metrics like operations per second (hz), margin of error (rme), and sample count. ```json [ { "name": "Mapper#execute", "hz": 945768113.85, "rme": 1.02, "sampleCount": 100 } ] ``` -------------------------------- ### MinLength Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Shows the `@MinLength(min)` decorator, which validates that a string property has a minimum length. ```typescript class UserDto { @MinLength(3) username: string; } ``` -------------------------------- ### Troubleshooting TypeScript Decorator Errors in Data Mapper Source: https://github.com/isqanderm/data-mapper/blob/main/DOCUMENTATION_IMPROVEMENTS.md This snippet addresses common TypeScript decorator errors, explaining correct tsconfig.json configurations and TC39 Stage 3 decorator setup for the Data Mapper. It contrasts incorrect and correct usage patterns to guide developers. ```typescript // Incorrect tsconfig.json example (may cause errors) // { // "compilerOptions": { // "experimentalDecorators": false, // "emitDecoratorMetadata": false // } // } // Correct tsconfig.json example for decorator support // { // "compilerOptions": { // "experimentalDecorators": true, // "emitDecoratorMetadata": true, // "useDefineForClassFields": false // Often needed for Stage 3 decorators // } // } // Example of Stage 3 decorator setup (conceptual) // Ensure your environment supports Stage 3 decorators, potentially via Babel or newer TypeScript versions. // import { decorate } from 'some-decorator-library'; // // @decorate() // class MyClass {} ``` -------------------------------- ### Install om-data-mapper using npm Source: https://github.com/isqanderm/data-mapper/blob/main/ANNOUNCEMENT_v4.1.0.md Installs the om-data-mapper package version 4.1.0 using npm. This command is used to add the library as a project dependency for Node.js applications. ```bash npm install om-data-mapper@4.1.0 ``` -------------------------------- ### Compatibility API Source: https://github.com/isqanderm/data-mapper/blob/main/docs/transformer-usage.md This section covers the decorators and functions for the Compatibility API, designed to mimic class-transformer functionality. ```APIDOC ## Compatibility API ### Decorators - `@Expose(options?)` - **Description**: Exposes a property, making it visible for serialization/deserialization. - **Usage**: Apply to class properties. - `@Exclude(options?)` - **Description**: Excludes a property, hiding it from serialization/deserialization. - **Usage**: Apply to class properties. - `@Type(typeFunction, options?)` - **Description**: Specifies the type of a property, often used for nested objects or arrays. - **Usage**: Apply to class properties, providing a function that returns the type. - `@Transform(transformFn, options?)` - **Description**: Applies a transformation function to a property's value during serialization/deserialization. - **Usage**: Apply to class properties, passing the transformation function. - `@TransformClassToPlain(options?)` - **Description**: A method decorator that transforms class instances to plain objects. - **Usage**: Apply to methods within a class. - `@TransformClassToClass(options?)` - **Description**: A method decorator that transforms class instances to other class instances (cloning). - **Usage**: Apply to methods within a class. - `@TransformPlainToClass(classType, options?)` - **Description**: A method decorator that transforms plain objects to instances of a specified `classType`. - **Usage**: Apply to methods within a class. ### Functions - `plainToClass(Class, plain, options?)` - **Description**: Transforms a plain object (`plain`) into an instance of the specified `Class`. - **Usage**: `const instance = plainToClass(MyClass, { ... });` - `plainToInstance(Class, plain, options?)` - **Description**: An alias for `plainToClass`. - **Usage**: `const instance = plainToInstance(MyClass, { ... });` - `plainToClassFromExist(instance, plain, options?)` - **Description**: Updates an existing `instance` with properties from a `plain` object. - **Usage**: `plainToClassFromExist(myInstance, { ... });` - `classToPlain(instance, options?)` - **Description**: Transforms a class `instance` into a plain object. - **Usage**: `const plainObj = classToPlain(myInstance);` - `instanceToPlain(instance, options?)` - **Description**: An alias for `classToPlain`. - **Usage**: `const plainObj = instanceToPlain(myInstance);` - `classToClass(instance, options?)` - **Description**: Clones a class `instance` into a new instance of the same class. - **Usage**: `const clonedInstance = classToClass(myInstance);` - `instanceToInstance(instance, options?)` - **Description**: An alias for `classToClass`. - **Usage**: `const clonedInstance = instanceToInstance(myInstance);` - `serialize(instance, options?)` - **Description**: Serializes a class `instance` to a JSON string. - **Usage**: `const jsonString = serialize(myInstance);` - `deserialize(Class, json, options?)` - **Description**: Deserializes a JSON string into an instance of the specified `Class`. - **Usage**: `const instance = deserialize(MyClass, jsonString);` - `deserializeArray(Class, json, options?)` - **Description**: Deserializes a JSON string representing an array into an array of `Class` instances. - **Usage**: `const instances = deserializeArray(MyClass, jsonArrayString);` ``` -------------------------------- ### Conventional Commits Example Messages Source: https://github.com/isqanderm/data-mapper/blob/main/CONTRIBUTING.md Illustrates the format and types of commit messages used in the project, adhering to the Conventional Commits specification for better changelog generation and versioning. ```bash # Feature git commit -m "feat: add support for nested array mapping" # Bug fix git commit -m "fix: resolve issue with undefined values in deep mapping" # Documentation git commit -m "docs: update README with new examples" # Breaking change git commit -m "feat!: redesign mapper API BREAKING CHANGE: The create method now requires explicit type parameters" ``` -------------------------------- ### Run Comparison Benchmarks with Benchmark.js Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md This command executes a comparison benchmark file using ts-node, which is necessary for running TypeScript files directly. Ensure you are in the correct directory and have ts-node installed. ```bash npx ts-node comparisons/my-comparison/my-comparison.bench.ts ``` -------------------------------- ### Example Usage of class-transformer Compatibility Layer Source: https://github.com/isqanderm/data-mapper/blob/main/README.md Provides a practical example of using the om-data-mapper's class-transformer compatibility layer. It demonstrates defining classes with decorators like @Expose, @Transform, and @Type for data transformation. ```typescript import { plainToClass, Expose, Type, Transform } from 'om-data-mapper/class-transformer-compat'; class Address { @Expose() street: string; @Expose() city: string; } class User { @Expose() id: number; @Expose() @Transform(({ value }) => value.toUpperCase()) name: string; @Expose() @Type(() => Address) address: Address; @Exclude() password: string; } const plain = { id: 1, name: 'john', address: { street: '123 Main St', city: 'New York' }, password: 'secret' }; const user = plainToClass(User, plain); console.log(user.name); // 'JOHN' console.log(user.address instanceof Address); // true console.log(user.password); // undefined ``` -------------------------------- ### Add New Benchmark using Vitest Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/core/README.md Example TypeScript code demonstrating how to add a new benchmark using Vitest, including importing necessary utilities and defining a benchmark test. ```typescript import { bench, describe } from 'vitest'; import { Mapper } from '../../src/core/Mapper'; describe('My Benchmark', () => { const mapper = Mapper.create({ /* ... */ }); const data = { /* ... */ }; bench('My test', () => { mapper.execute(data); }); }); ``` -------------------------------- ### Decorator API Source: https://github.com/isqanderm/data-mapper/blob/main/docs/transformer-usage.md This section details the decorators and functions available in the Decorator API for class and property mapping. ```APIDOC ## Decorator API ### Class Decorators - `@Mapper(options?)` - **Description**: Marks a class as a mapper, enabling it to transform objects from a `Source` type to a `Target` type. - **Usage**: Apply this decorator to your mapper class definition. ### Property Decorators - `@Map(sourcePath)` - **Description**: Specifies the source path for a property to be mapped from. - **Usage**: Use on a property within a mapper class to define its source. - `@MapFrom(transformer)` - **Description**: Maps a property using a provided transformer function. - **Usage**: Apply to a property, passing a function that handles the transformation logic. - `@Transform(transformer)` - **Description**: Transforms a property's value after it has been mapped. - **Usage**: Use on a property to apply a transformation function to its mapped value. - `@Default(value)` - **Description**: Provides a default value for a property if no value is mapped from the source. - **Usage**: Apply to a property to set a fallback value. - `@When(condition)` - **Description**: Enables conditional mapping based on a specified condition. - **Usage**: Use on a property to control mapping based on certain criteria. - `@Ignore()` - **Description**: Excludes a property from the mapping process. - **Usage**: Apply to a property to prevent it from being mapped. - `@MapNested(MapperClass)` - **Description**: Maps a nested object using a specified nested mapper class. - **Usage**: Use on a property representing a nested object structure. ### Functions - `plainToInstance(MapperClass, source)` - **Description**: Transforms a plain object (`source`) into an instance of the specified `MapperClass`. - **Usage**: `const instance = plainToInstance(MyMapper, { ... });` - `plainToInstanceArray(MapperClass, sources)` - **Description**: Transforms an array of plain objects (`sources`) into an array of `MapperClass` instances. - **Usage**: `const instances = plainToInstanceArray(MyMapper, [{ ... }, { ... }]);` - `tryPlainToInstance(MapperClass, source)` - **Description**: Attempts to transform a plain object into an instance, returning an error if the transformation fails. - **Usage**: `const result = tryPlainToInstance(MyMapper, { ... }); // result is either instance or error` - `createMapper(MapperClass)` - **Description**: Creates a new instance of a mapper. - **Usage**: `const mapper = createMapper(MyMapper);` - `getMapper(MapperClass)` - **Description**: Retrieves the singleton instance of a mapper. - **Usage**: `const mapper = getMapper(MyMapper);` ``` -------------------------------- ### API Reference - Functions Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Lists the core validation functions available in the Data Mapper library, including their purpose and usage. ```APIDOC ## API Reference - Functions ### Description This section details the primary functions provided by the Data Mapper validation library for performing validation operations on objects and arrays. ### Method **Not Applicable** ### Endpoint **Not Applicable** ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Example usage of validateSync import { validateSync } from 'om-data-mapper/class-validator-compat'; const errors = validateSync(dto); ``` ### Response #### Success Response (200) **Not Applicable** #### Response Example **Not Applicable** ### Functions - `validate(object, options?)`: Performs asynchronous validation. - `validateSync(object, options?)`: Performs synchronous validation. - `validateOrReject(object, options?)`: Performs asynchronous validation and throws an error if validation fails. - `validateOrRejectSync(object, options?)`: Performs synchronous validation and throws an error if validation fails. - `validateMany(objects, options?)`: Validates an array of objects asynchronously. - `validateManySync(objects, options?)`: Validates an array of objects synchronously. ``` -------------------------------- ### Troubleshooting Import Errors Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/core/README.md Example TypeScript code snippet showing the correct way to import the Mapper class to avoid import errors in benchmarks. ```typescript import { Mapper } from '../../src/core/Mapper'; ``` -------------------------------- ### TypeScript Usage Example for Data Validation Source: https://github.com/isqanderm/data-mapper/blob/main/ANNOUNCEMENT_v4.1.0.md Demonstrates how to use om-data-mapper with TypeScript for data validation. It defines a DTO class with decorators for validation rules and then uses the 'validate' function to check an instance of the DTO. This example shows how to import validation decorators and the validate function. ```typescript import { IsString, MinLength, IsNumber, Min, validate } from 'om-data-mapper/class-validator-compat'; class CreateUserDto { @IsString() @MinLength(3) name!: string; @IsNumber() @Min(0) age!: number; } const user = new CreateUserDto(); user.name = 'Jo'; // Too short user.age = -5; // Too small const errors = await validate(user); // Validation errors returned ``` -------------------------------- ### API Reference - Decorators Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Provides a comprehensive list of decorators available for defining validation rules on DTO properties. ```APIDOC ## API Reference - Decorators ### Description This section lists the various decorators provided by the Data Mapper validation library that can be applied to class properties to define validation constraints. ### Method **Not Applicable** ### Endpoint **Not Applicable** ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { IsString, MinLength, MaxLength, Matches } from 'om-data-mapper/class-validator-compat'; class UserDto { @IsString() @MinLength(3) @MaxLength(20) @Matches(/^[a-zA-Z0-9]+$/) username: string; } ``` ### Response #### Success Response (200) **Not Applicable** #### Response Example **Not Applicable** ### Decorators - **Common**: `@IsOptional()`, `@IsDefined()`, `@IsNotEmpty()`, `@Equals()`, `@NotEquals()`, `@IsIn()`, `@IsNotIn()` - **String**: `@IsString()`, `@MinLength()`, `@MaxLength()`, `@Length()`, `@IsEmail()`, `@IsURL()`, `@IsUUID()`, `@Matches()` - **Number**: `@IsNumber()`, `@IsInt()`, `@Min()`, `@Max()`, `@IsPositive()`, `@IsNegative()` - **Date**: `@MinDate()`, `@MaxDate()` - **Array**: `@IsArray()`, `@ArrayNotEmpty()`, `@ArrayMinSize()`, `@ArrayMaxSize()`, `@ArrayUnique()` - **Type**: `@IsBoolean()`, `@IsDate()`, `@IsObject()`, `@IsEnum()`, `@IsInstance()` - **Nested**: `@ValidateNested()`, `@ValidateIf()`, `@ValidatePromise()` - **Custom**: `@Validate()`, `@ValidateBy()`, `@ValidatorConstraint()` ``` -------------------------------- ### Run all comparisons summary (Bash) Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/README.md Executes a summarized run of all comparison benchmarks defined in the project. Assumes execution from the 'benchmarks' directory. ```bash # From benchmarks directory npm run bench:comparisons ``` -------------------------------- ### Performance Tip: Reuse Mapper Instances (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/migration-class-transformer.md Demonstrates a performance optimization by reusing mapper instances instead of creating new ones for each transformation, leading to significantly faster data mapping. ```ts // ❌ Slow // data.map(item => plainToClass(UserDTO, item)); // ✅ Fast // const mapper = getMapper(UserMapper); // data.map(item => mapper.transform(item)); ``` -------------------------------- ### IsDefined Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Illustrates the `@IsDefined()` decorator, used to ensure that a property's value is not `undefined`. ```typescript class UserDto { @IsDefined() name: string; } ``` -------------------------------- ### IsString Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Illustrates the `@IsString()` decorator, used to validate that a property's value is of the string type. ```typescript class UserDto { @IsString() name: string; } ``` -------------------------------- ### Run All Core Benchmarks using npm or npx Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/core/README.md Commands to execute all core benchmarks from the project root or the benchmarks directory using npm or npx with Vitest. ```bash # From project root npm run bench:core # Or from benchmarks directory npx vitest bench core/ ``` -------------------------------- ### Performance Tip: Use Batch Functions (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/migration-class-transformer.md Highlights the efficiency of using batch functions like 'plainToInstanceArray' for transforming arrays of data, offering better performance than individual transformations. ```ts // ✅ More efficient // plainToInstanceArray(UserMapper, data); ``` -------------------------------- ### Equals Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Demonstrates the `@Equals(value)` decorator, which checks if the property's value is strictly equal to a specified value. ```typescript class ConfigDto { @Equals('production') environment: string; } ``` -------------------------------- ### TypeScript Configuration for Decorators Source: https://github.com/isqanderm/data-mapper/blob/main/docs/migration-class-transformer.md Provides the necessary 'tsconfig.json' settings to enable TC39 Stage 3 decorators and disable legacy experimental decorators, which is required for 'om-data-mapper'. ```json { "compilerOptions": { "target": "ES2022", "experimentalDecorators": false, // Do not use legacy decorators "emitDecoratorMetadata": false // Not needed } } ``` -------------------------------- ### Asynchronous Object Validation (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Example of using the `validate` function to asynchronously validate an object. It checks for errors and logs them if validation fails. ```typescript const errors = await validate(userDto); if (errors.length > 0) { console.log('Validation failed:', errors); } ``` -------------------------------- ### Troubleshoot TypeScript Errors in Benchmarks Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md This set of commands helps resolve TypeScript-related issues within the benchmark environment. It includes installing dependencies and checking the TypeScript configuration by running the TypeScript compiler with the '--noEmit' flag. ```bash # Make sure dependencies are installed cd benchmarks npm install # Check TypeScript configuration npx tsc --noEmit ``` -------------------------------- ### Quick Start: Decorator API for Object Transformation Source: https://github.com/isqanderm/data-mapper/blob/main/docs-ru/transformer-usage.md Demonstrates the recommended Decorator API for transforming a source object to a DTO. It uses @Mapper and @MapFrom decorators to define the mapping logic. ```typescript import { Mapper, MapFrom, plainToInstance } from 'om-data-mapper'; type UserSource = { firstName: string; lastName: string; age: number; }; type UserDTO = { fullName: string; isAdult: boolean; }; @Mapper() class UserMapper { @MapFrom((src: UserSource) => `${src.firstName} ${src.lastName}`) fullName!: string; @MapFrom((src: UserSource) => src.age >= 18) isAdult!: boolean; } const source = { firstName: 'John', lastName: 'Doe', age: 30 }; const result = plainToInstance(UserMapper, source); // { fullName: 'John Doe', isAdult: true } ``` -------------------------------- ### NotEquals Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Illustrates the `@NotEquals(value)` decorator, used to ensure that a property's value is not strictly equal to a specified value. ```typescript class UserDto { @NotEquals('admin') role: string; } ``` -------------------------------- ### Performance Tip: Enable Unsafe Mode (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/migration-class-transformer.md Shows how to enable 'unsafe' mode in the @Mapper decorator for potentially faster transformations when dealing with trusted data sources. ```ts @Mapper({ unsafe: true }) class FastMapper { /* ... */ } ``` -------------------------------- ### Add new comparison benchmark structure (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/README.md Provides a template for adding a new benchmark comparison. It includes setting up the directory, creating a benchmark file, importing libraries, defining test scenarios using the 'benchmark' library, and handling results. ```bash mkdir comparisons/my-library-comparison cd comparisons/my-library-comparison ``` ```typescript // my-library-comparison.bench.ts import { Suite } from 'benchmark'; import 'reflect-metadata'; // Import libraries to compare import { /* om-data-mapper */ } from '../../src'; import { /* other-library */ } from 'other-library'; // Define test scenarios const suite = new Suite(); suite .add('om-data-mapper', function () { // Your code }) .add('other-library', function () { // Comparison code }) .on('cycle', function (event: any) { console.log(String(event.target)); }) .on('complete', function (this: any) { // Calculate and display results }) .run({ async: false }); ``` -------------------------------- ### IsNotEmpty Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Shows the `@IsNotEmpty()` decorator, which validates that a property's value is not empty (e.g., not an empty string, array, or object). ```typescript class UserDto { @IsNotEmpty() name: string; } ``` -------------------------------- ### Custom Asynchronous Validators Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Explains how to implement custom asynchronous validators, which are useful for validation logic that requires I/O operations like database lookups. ```APIDOC ## Async Custom Validators ### Description Implement custom asynchronous validators for validation logic that involves asynchronous operations, such as checking external services or databases. The `validate` function from the library is used to trigger these async validations. ### Method **Not Applicable** (This describes a concept, not an endpoint) ### Endpoint **Not Applicable** ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **Not Applicable** ### Request Example ```typescript @ValidatorConstraint({ name: 'isUserAlreadyExist', async: true }) class IsUserAlreadyExistConstraint implements ValidatorConstraintInterface { async validate(value: any, args: ValidationArguments): Promise { // Check database const user = await database.findUserByEmail(value); return !user; // Return false if user exists } defaultMessage(args: ValidationArguments): string { return 'User with this email already exists'; } } class CreateUserDto { @Validate(IsUserAlreadyExistConstraint) email: string; } // Must use async validate const errors = await validate(dto); ``` ### Response #### Success Response (200) **Not Applicable** #### Response Example **Not Applicable** ``` -------------------------------- ### IsOptional Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Demonstrates the `@IsOptional()` decorator, which marks a property as optional, meaning validation is skipped if the property's value is `undefined`. ```typescript class UserDto { @IsOptional() @IsString() middleName?: string; } ``` -------------------------------- ### Class-Validator Migration Example Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/validation-comparison/RESULTS.md Demonstrates how to migrate from using class-validator to om-data-mapper by changing the import statement. This highlights om-data-mapper's compatibility and aims for a seamless transition for existing projects. ```typescript // Before (class-validator) import { validateSync } from 'class-validator'; // After (om-data-mapper) import { validateSync } from 'om-data-mapper/class-validator-compat'; // Same decorators, same API, 20,000-60,000% faster! ``` -------------------------------- ### Push Branch and Submit Pull Request Source: https://github.com/isqanderm/data-mapper/blob/main/CONTRIBUTING.md Instructions on how to push your local feature branch to your fork on GitHub and initiate the pull request process. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### IsNotIn Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Demonstrates the `@IsNotIn(values)` decorator, which ensures that a property's value is not present within a given array of disallowed values. ```typescript class UserDto { @IsNotIn(['root', 'administrator']) username: string; } ``` -------------------------------- ### Running Tests and Checking Coverage with npm Source: https://github.com/isqanderm/data-mapper/blob/main/CONTRIBUTING.md These commands are used to execute tests and verify code coverage locally. Running `npm test` executes all tests and generates coverage reports, while `npm run test:watch` provides an interactive watch mode. `npx vitest` allows running specific test files. ```bash # Run all tests with coverage npm test # Run tests in watch mode npm run test:watch # Run specific test file npx vitest tests/smoke.test.ts ``` -------------------------------- ### IsIn Decorator Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Shows the `@IsIn(values)` decorator, which validates that a property's value is present within a given array of allowed values. ```typescript class UserDto { @IsIn(['admin', 'user', 'guest']) role: string; } ``` -------------------------------- ### Basic Object Validation with Decorators (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Demonstrates basic object validation using decorators from om-data-mapper's class-validator-compat. It shows how to define a DTO with validation rules and then validate an instance of it. ```typescript import { IsString, IsEmail, MinLength, validate } from 'om-data-mapper/class-validator-compat'; class UserDto { @IsString() @MinLength(3) name: string; @IsEmail() email: string; } const user = new UserDto(); user.name = 'Jo'; // Too short user.email = 'invalid-email'; const errors = await validate(user); console.log(errors); // [ // { // property: 'name', // constraints: { minLength: 'name must be at least 3 characters' } // }, // { // property: 'email', // constraints: { isEmail: 'email must be a valid email' } // } // ] ``` -------------------------------- ### Run multi-library comparison benchmark (Bash) Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/README.md Executes the benchmark suite comparing om-data-mapper against multiple other mapping libraries including class-transformer, automapper-ts, morphism, and object-mapper. ```bash npx ts-node comparisons/library-comparison/compare-benchmark.ts ``` -------------------------------- ### Validate Date After or Equal - TypeScript Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md Ensures a date property is on or after a specified date using the @MinDate decorator. This is useful for setting valid start dates for events or periods. It takes a Date object as an argument. ```typescript class EventDto { @MinDate(new Date('2024-01-01')) startDate: Date; } ``` -------------------------------- ### Performance Profiling of Validation Compilation and Execution Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-jit-internals.md Provides code examples for profiling the performance of validation compilation and execution using `console.time` and `console.timeEnd` in JavaScript. This helps in identifying performance bottlenecks. ```typescript console.time('compilation'); const validator = compileValidator(metadata); console.timeEnd('compilation'); console.time('execution'); const errors = validator(object, options); console.timeEnd('execution'); ``` -------------------------------- ### Get Singleton Mapper Instance with getMapper Source: https://github.com/isqanderm/data-mapper/blob/main/docs/transformer-usage.md The getMapper function retrieves or creates a singleton instance of a mapper class. Using a singleton ensures that only one instance of the mapper is active, which can be beneficial for managing state and resources. ```typescript const mapper = getMapper(UserMapper); const result = mapper.transform(source); ``` -------------------------------- ### Run class-transformer comparison benchmark (Bash) Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/README.md Executes the benchmark suite for comparing om-data-mapper's class-transformer compatibility layer with the original class-transformer library. This script is typically run from the benchmarks directory. ```bash npx ts-node comparisons/class-transformer-comparison/class-transformer-comparison.bench.ts ``` -------------------------------- ### Run validation comparison benchmark (Bash) Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/comparisons/README.md Executes the benchmark suite comparing om-data-mapper's validation engine against class-validator. This command requires a specific tsconfig.json file for the validation comparison. ```bash npx ts-node --project comparisons/validation-comparison/tsconfig.json \n comparisons/validation-comparison/validation-comparison.bench.ts ``` -------------------------------- ### Leveraging Nested Mappers (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs/transformer-usage.md Illustrates the use of nested mappers for handling complex object structures. The example shows how to use the @MapNested decorator to reuse an existing `AddressMapper` for the `address` property, promoting modularity and reducing code duplication. ```typescript // ✅ Good: Reusable nested mapper @MapNested(AddressMapper) address!: Address; // ❌ Bad: Inline transformation @MapFrom((src) => ({ street: src.address.street, city: src.address.city })) address!: Address; ``` -------------------------------- ### Add Comparison Benchmark with Benchmark.js Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md This snippet shows how to set up a benchmark for comparing different libraries using Benchmark.js. It involves creating a new directory in 'comparisons/', importing 'Suite' from 'benchmark', and adding test cases with the '.add()' method. The 'cycle' event is used to log results. ```typescript import { Suite } from 'benchmark'; import 'reflect-metadata'; const suite = new Suite(); suite .add('om-data-mapper', function () { // Your code }) .add('other-library', function () { // Comparison code }) .on('cycle', function (event: any) { console.log(String(event.target)); }) .run({ async: false }); ``` -------------------------------- ### Validate Hex Color Format with IsHexColor Decorator Source: https://github.com/isqanderm/data-mapper/blob/main/docs/validation-usage.md The `@IsHexColor()` decorator checks if a string is a valid hexadecimal color code, typically starting with '#' followed by 3 or 6 hexadecimal characters (e.g., '#FFF', '#FF0000'). This is useful for UI theme settings. ```typescript class ThemeDto { @IsHexColor() primaryColor: string; } ``` -------------------------------- ### Run Core Benchmarks with npm Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md Execute core functionality benchmarks for om-data-mapper using npm scripts. This command initiates tests for the fundamental mapping engine performance. ```bash # From project root npm run bench:core ``` -------------------------------- ### Run Tests and Linting with npm Source: https://github.com/isqanderm/data-mapper/blob/main/CONTRIBUTING.md Commands to execute the project's test suite and run code linting checks using npm. These commands help ensure code quality and identify potential issues. ```bash npm test npm run lint ``` -------------------------------- ### Run Specific Core Benchmark using npx Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/core/README.md Commands to execute individual core benchmark files (simple, complex, nested, array) using npx and Vitest. ```bash npx vitest bench core/simple.bench.ts npx vitest bench core/complex.bench.ts npx vitest bench core/nested.bench.ts npx vitest bench core/array.bench.ts ``` -------------------------------- ### Run All ESM Tests with npm Source: https://github.com/isqanderm/data-mapper/blob/main/INTEGRATION_SUMMARY.md This command executes the complete ESM test suite, including integration, smoke, and simulation tests. It ensures all aspects of ESM compatibility are validated. ```bash npm run test:esm ``` -------------------------------- ### Add Core Benchmark with Vitest Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md This snippet demonstrates how to create and define a new benchmark using Vitest. It requires importing 'bench' and 'describe' from 'vitest' and the 'Mapper' class from the project's core. The benchmark is placed in a '.bench.ts' file within the 'core/' directory. ```typescript import { bench, describe } from 'vitest'; import { Mapper } from '../../src/core/Mapper'; describe('My Benchmark', () => { bench('Test name', () => { // Your benchmark code }); }); ``` -------------------------------- ### Example Usage of Class Transformation Options (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs-ru/transformer-usage.md This example demonstrates how to apply `ClassTransformOptions` when using `plainToClass`. Options like `excludeExtraneousValues`, `groups`, and `version` can be used to customize the transformation process. ```typescript const user = plainToClass(UserDTO, plain, { excludeExtraneousValues: true, // Only @Expose properties groups: ['admin'], // Only admin group version: 2.0 // Version 2.0 properties }); ``` -------------------------------- ### README Badges for om-data-mapper Source: https://github.com/isqanderm/data-mapper/blob/main/ANNOUNCEMENT_v4.1.0.md Markdown snippets to display version, test coverage, performance, and test status badges in a README.md file. These badges link to relevant npm, GitHub, or documentation pages. ```markdown [![npm version](https://img.shields.io/npm/v/om-data-mapper.svg)](https://www.npmjs.com/package/om-data-mapper) ``` ```markdown [![Coverage](https://img.shields.io/badge/coverage-95.08%25-brightgreen.svg)](https://github.com/Isqanderm/data-mapper) ``` ```markdown [![Performance](https://img.shields.io/badge/performance-70--909x%20faster-brightgreen.svg)](https://github.com/Isqanderm/data-mapper/blob/main/benchmarks/README.md) ``` ```markdown [![Tests](https://img.shields.io/badge/tests-518%20passing-brightgreen.svg)](https://github.com/Isqanderm/data-mapper) ``` -------------------------------- ### Run Specific ESM Test Suites with npm Source: https://github.com/isqanderm/data-mapper/blob/main/INTEGRATION_SUMMARY.md These commands allow for targeted execution of specific ESM test suites: integration tests for comprehensive validation, simple smoke tests for quick checks, and simulation tests for real-world scenarios. ```bash npm run test:esm:integration # Comprehensive ``` ```bash npm run test:esm:simple # Quick smoke test ``` ```bash npm run test:esm:simulation # Real-world scenarios ``` -------------------------------- ### Run Class-Transformer Comparison Benchmark Source: https://github.com/isqanderm/data-mapper/blob/main/benchmarks/README.md Execute the benchmark comparing om-data-mapper with class-transformer using ts-node. This tests the compatibility layer and performance differences. ```bash # class-transformer comparison cd benchmarks npx ts-node comparisons/class-transformer-comparison/class-transformer-comparison.bench.ts ``` -------------------------------- ### Advanced Nested Objects with @Type Example (TypeScript) Source: https://github.com/isqanderm/data-mapper/blob/main/docs-ru/transformer-usage.md This advanced example showcases how to use the @Type decorator with nested objects and arrays. It defines classes for `Photo`, `Album`, and `UserDTO`, demonstrating deep nesting and type specification for arrays of custom objects and dates. ```typescript class Photo { @Expose() url: string; @Expose() @Type(() => Date) uploadedAt: Date; } class Album { @Expose() name: string; @Expose() @Type(() => Photo) photos: Photo[]; } class UserDTO { @Expose() name: string; @Expose() @Type(() => Album) albums: Album[]; } const plain = { name: 'John', albums: [ { name: 'Vacation', photos: [ { url: 'photo1.jpg', uploadedAt: '2024-01-01' }, { url: 'photo2.jpg', uploadedAt: '2024-01-02' } ] } ] }; const user = plainToClass(UserDTO, plain); console.log(user.albums[0].photos[0] instanceof Photo); // true console.log(user.albums[0].photos[0].uploadedAt instanceof Date); // true ``` -------------------------------- ### Run All Project Tests with npm Source: https://github.com/isqanderm/data-mapper/blob/main/INTEGRATION_SUMMARY.md This command runs all tests within the project, including both unit tests and the comprehensive ESM tests. It provides a complete validation of the codebase. ```bash npm run test:all # Unit tests + ESM tests ```