### Install mapper-factory with npm Source: https://github.com/lucaangrisani/mapper-factory/blob/master/README.md This command installs the mapper-factory package using npm. Ensure you have Node.js and npm installed on your system. ```bash npm i mapper-factory ``` -------------------------------- ### Install mapper-factory with yarn Source: https://github.com/lucaangrisani/mapper-factory/blob/master/README.md This command installs the mapper-factory package using yarn. Ensure you have Node.js and yarn installed on your system. ```bash yarn add mapper-factory ``` -------------------------------- ### Complex Field Mapping Example with User Class Source: https://github.com/lucaangrisani/mapper-factory/blob/master/README.md Provides a detailed example of the 'User' class with multiple '@MapField' decorators, including transformations for arrays and nested objects. It also shows how to instantiate and map complex user data. ```typescript @MapClass() class User { id: string; username: string; @MapField({ src: 'firstName' }) name: string; @MapField({ src: 'lastName' }) surname: string; @MapField({ src: 'rolesToMap', transformer: (arr) => arr.map(role => role + " TEST TRASFORMER"), reverser: (arr) => arr.map(role => role.replace(" TEST TRASFORMER", "")), }) roles?: string[]; @MapField({ transformer: (arr) => arr.map(user => new User(user)) }) employees?: User[]; @MapField({ transformer: (user) => new User(user) }) boss?: User; } interface User extends MapInterface { } let emp1: User = new User().from({ firstName: "Summer", lastName: "Smith" }); let emp2: User = new User().from({ firstName: "Morty", lastName: "Smith" }); let u = new User().from({ firstName: "Rick", lastName: "Sanchez", employees: [emp1.toMap(), emp2.toMap()], rolesToMap: ["CEO", "EMPLOYEE"] }); ``` -------------------------------- ### Advanced MapInterface Methods Source: https://github.com/lucaangrisani/mapper-factory/blob/master/README.md Illustrates the usage of various utility methods provided by MapInterface, including 'toModel' for creating instances from models, 'empty' and 'filled' for checking object state, 'get' and 'set' for property access, and 'copy' for deep copying. ```typescript const yourInstance: YourClass = new YourClass().from(/** YOUR OBJECT TO MAP HERE */); const reverseMappedObject: Object = yourInstance.toMap(); const anotherInstance: YourClass = new YourClass.toModel(yourInstance); const isEmpty: boolean = yourInstance.empty(); const isFilled: boolean = yourInstance.filled(); const specificProp: T = yourInstance.get('specificProp') as T; yourInstance.set('specificProp', /** NEW VALUE FOR 'specificProp' */); const yourInstanceCopy: YourClass = yourInstance.copy(); ``` -------------------------------- ### Untitled No description -------------------------------- ### Deep Property Access with get() Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The get() method retrieves a property value using a string path. It supports accessing nested objects and array elements by index, enabling deep property access within complex structures. ```typescript import { MapClass, MapInterface, ArrayField, ObjectField } from 'mapper-factory'; @MapClass() class Item { name: string; quantity: number; } interface Item extends MapInterface {} @MapClass() class Warehouse { location: string; @ArrayField(Item) inventory: Item[]; } interface Warehouse extends MapInterface {} const warehouse = new Warehouse().from({ location: 'North', inventory: [ { name: 'Widget A', quantity: 100 }, { name: 'Widget B', quantity: 50 } ] }); console.log(warehouse.get('location')); // 'North' console.log(warehouse.get('inventory[0].name')); // 'Widget A' console.log(warehouse.get('inventory[1].quantity')); // 50 ``` -------------------------------- ### Basic Class Mapping with @MapClass Decorator Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The @MapClass decorator augments a class with mapping capabilities. It adds methods to the class prototype for transforming objects to and from plain JSON. This example shows a simple User class mapped to and from a plain object. ```typescript import { MapClass, MapInterface } from 'mapper-factory'; @MapClass() class User { id: string; name: string; email: string; } interface User extends MapInterface {} // Create instance from plain object const user = new User().from({ id: '1', name: 'John Doe', email: 'john@example.com' }); console.log(user); // User { id: '1', name: 'John Doe', email: 'john@example.com' } // Convert back to plain object const plainObject = user.toMap(); console.log(plainObject); // { id: '1', name: 'John Doe', email: 'john@example.com' } ``` -------------------------------- ### Advanced Field Mapping with @MapField Decorator Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The @MapField decorator allows detailed configuration for individual property mappings. It supports renaming source fields (`src`), applying custom transformation functions (`transformer`), and defining reversal logic (`reverser`) for bidirectional mapping. This example demonstrates mapping `firstName` to `name`, `lastName` to `surname`, and transforming an array of roles. ```typescript import { MapClass, MapInterface, MapField } from 'mapper-factory'; @MapClass() class Employee { @MapField({ src: 'firstName' }) name: string; @MapField({ src: 'lastName' }) surname: string; @MapField({ src: 'rolesToMap', transformer: (roles) => roles?.map(role => role.toUpperCase()), reverser: (roles) => roles?.map(role => role.toLowerCase()) }) roles: string[]; } interface Employee extends MapInterface {} const jsonData = { firstName: 'Alice', lastName: 'Johnson', rolesToMap: ['developer', 'architect'] }; const employee = new Employee().from(jsonData); console.log(employee.name); // 'Alice' console.log(employee.roles); // ['DEVELOPER', 'ARCHITECT'] const reversed = employee.toMap(); console.log(reversed); // { firstName: 'Alice', lastName: 'Johnson', rolesToMap: ['developer', 'architect'] } ``` -------------------------------- ### Array Mapping with @ArrayField Decorator Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The @ArrayField decorator simplifies mapping arrays of objects to arrays of class instances. It automatically handles the transformation of each element in the array, ensuring type safety. This example shows mapping an array of location data to `Address` instances within a `Company` class. ```typescript import { MapClass, MapInterface, ArrayField } from 'mapper-factory'; @MapClass() class Address { street: string; city: string; } interface Address extends MapInterface
{} @MapClass() class Company { name: string; @ArrayField(Address) locations: Address[]; } interface Company extends MapInterface {} const companyData = { name: 'Tech Corp', locations: [ { street: '123 Main St', city: 'New York' }, { street: '456 Oak Ave', city: 'San Francisco' } ] }; const company = new Company().from(companyData); console.log(company.locations[0] instanceof Address); // true console.log(company.locations[0].city); // 'New York' const serialized = company.toMap(); console.log(serialized.locations); // [{ street: '123 Main St', city: 'New York' }, ...] ``` -------------------------------- ### Nested Object Mapping with @ObjectField Decorator Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The @ObjectField decorator enables mapping of nested plain objects to class instances, facilitating the handling of complex object hierarchies. It ensures type safety for deeply nested structures. This example demonstrates mapping a `Department` object within a `Manager` class. ```typescript import { MapClass, MapInterface, ObjectField } from 'mapper-factory'; @MapClass() class Department { name: string; budget: number; } interface Department extends MapInterface {} @MapClass() class Manager { name: string; @ObjectField(Department) department: Department; } interface Manager extends MapInterface {} const managerData = { name: 'Sarah Williams', department: { name: 'Engineering', budget: 500000 } }; const manager = new Manager().from(managerData); console.log(manager.department instanceof Department); // true console.log(manager.department.budget); // 500000 const mapped = manager.toMap(); console.log(mapped.department); // { name: 'Engineering', budget: 500000 } ``` -------------------------------- ### Instantiating and Mapping Objects with MapInterface Source: https://github.com/lucaangrisani/mapper-factory/blob/master/README.md Demonstrates how to create a new instance of a mapped class and use the 'from' method to map an object to this instance. It also shows how to use the 'toMap' method for reverse mapping. ```typescript const yourInstance: YourClass = new YourClass().from(/** YOUR OBJECT TO MAP HERE*/); const reversedMapping: Object = yourInstance.toMap(); ``` -------------------------------- ### Untitled No description -------------------------------- ### Create Instances from Plain Objects with from() Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The from() method instantiates a class from a plain JavaScript object. It applies mapping rules defined by decorators like @MapField and @ArrayField, including custom transformers for data conversion. ```typescript import { MapClass, MapInterface, MapField, ArrayField } from 'mapper-factory'; @MapClass() class Product { @MapField({ src: 'productName' }) name: string; @MapField({ src: 'price_cents', transformer: (cents) => cents / 100 }) price: number; } interface Product extends MapInterface {} @MapClass() class Order { orderId: string; @ArrayField(Product) items: Product[]; } interface Order extends MapInterface {} const orderData = { orderId: 'ORD-12345', items: [ { productName: 'Laptop', price_cents: 99999 }, { productName: 'Mouse', price_cents: 2500 } ] }; const order = new Order().from(orderData); console.log(order.items[0].price); // 999.99 console.log(order.items[1].name); // 'Mouse' ``` -------------------------------- ### Basic Class Mapping with MapClass Decorator Source: https://github.com/lucaangrisani/mapper-factory/blob/master/README.md Defines a class 'YourClass' that extends 'YourCustomClassToExtend' and implements MapInterface. This allows for easy object mapping using the 'from' and 'toMap' methods. ```typescript @MapClass() class YourClass extends YourCustomClassToExtend { /** YOUR PROPERTIES */ } interface YourClass extends MapInterface { } ``` -------------------------------- ### Create New Instances with toModel() Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The toModel() method creates a new instance of the same class from an existing instance. It performs a shallow copy of properties without applying any mapping transformations, ensuring a distinct object. ```typescript import { MapClass, MapInterface, MapField } from 'mapper-factory'; @MapClass() class Profile { username: string; @MapField({ src: 'full_name' }) displayName: string; } interface Profile extends MapInterface {} const original = new Profile().from({ username: 'jdoe', full_name: 'John Doe' }); const duplicate = new Profile().toModel(original); console.log(duplicate.username); // 'jdoe' console.log(duplicate.displayName); // 'John Doe' console.log(duplicate !== original); // true (different instance) ``` -------------------------------- ### Field Mapping with MapField Decorator and Transformers Source: https://github.com/lucaangrisani/mapper-factory/blob/master/README.md Shows how to use the '@MapField' decorator to map class properties to source fields, including nested paths. It also demonstrates the use of 'transformer' and 'reverser' functions for data transformation during mapping and reverse mapping. ```typescript @MapClass() class User { @MapField({ src: 'firstName' }) name: string; @MapField({ src: 'obj.obj[0][1]', transformer: (arr) => arr.map(role => role + " TEST TRASFORMER"), reverser: (arr) => arr.map(role => role.replace(" TEST TRASFORMER", "")), }) roles?: string[]; @MapField({ transformer: (user) => new User(user) }) boss: User; } interface User extends MapInterface { } ``` -------------------------------- ### Convert Instances to Plain Objects with toMap() Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The toMap() method converts a class instance back into a plain JavaScript object. It uses the reverse transformations defined in decorators and maps properties to their original source names. ```typescript import { MapClass, MapInterface, MapField } from 'mapper-factory'; @MapClass() class Account { @MapField({ src: 'account_number', transformer: (num) => `ACC-${num}`, reverser: (formatted) => formatted.replace('ACC-', '') }) accountNumber: string; @MapField({ src: 'balance_cents', transformer: (cents) => cents / 100, reverser: (dollars) => Math.round(dollars * 100) }) balance: number; } interface Account extends MapInterface {} const account = new Account().from({ account_number: '12345', balance_cents: 150000 }); console.log(account.accountNumber); // 'ACC-12345' console.log(account.balance); // 1500.00 const plainObject = account.toMap(); console.log(plainObject); // { account_number: '12345', balance_cents: 150000 } ``` -------------------------------- ### Untitled No description -------------------------------- ### Create Deep Copy of Class Instance (TypeScript) Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The copy() method generates a deep copy of a class instance. It achieves this by first converting the instance to a plain JavaScript object and then back into a new class instance. This ensures that the copied object is completely independent of the original. ```typescript import { MapClass, MapInterface, ObjectField } from 'mapper-factory'; @MapClass() class Settings { theme: string; notifications: boolean; } interface Settings extends MapInterface {} @MapClass() class UserProfile { username: string; @ObjectField(Settings) settings: Settings; } interface UserProfile extends MapInterface {} const original = new UserProfile().from({ username: 'alice', settings: { theme: 'dark', notifications: true } }); const copy = original.copy(); copy.settings.theme = 'light'; console.log(original.settings.theme); // 'dark' console.log(copy.settings.theme); // 'light' console.log(copy !== original); // true ``` -------------------------------- ### Untitled No description -------------------------------- ### Check if Instance Has No Defined Properties (TypeScript) Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The empty() method returns true if an instance has no properties that are defined (i.e., all properties are either undefined or null). This is useful for determining if an object has been populated with any data. Note that properties initialized with default values might prevent this method from returning true. ```typescript import { MapClass, MapInterface, MapField } from 'mapper-factory'; @MapClass() class Contact { @MapField({ transformer: (value) => value || 'unknown', initialize: true }) name: string; email: string; phone: string; } interface Contact extends MapInterface {} const emptyContact = new Contact().from({}); console.log(emptyContact.empty()); // false (name initialized to 'unknown') const contact = new Contact(); console.log(contact.empty()); // true (no properties set) ``` -------------------------------- ### Handle ISO Dates with @DateField Decorator Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The @DateField decorator automatically converts ISO date strings to JavaScript Date objects during deserialization and serializes Date objects back to ISO strings. It simplifies date handling in mapped classes. ```typescript import { MapClass, MapInterface, DateField } from 'mapper-factory'; @MapClass() class Event { title: string; @DateField() startDate: Date; @DateField() endDate: Date; } interface Event extends MapInterface {} const eventData = { title: 'Annual Conference', startDate: '2024-03-15T09:00:00Z', endDate: '2024-03-17T18:00:00Z' }; const event = new Event().from(eventData); console.log(event.startDate instanceof Date); // true console.log(event.startDate.getFullYear()); // 2024 const serialized = event.toMap(); console.log(serialized.startDate); // '2024-03-15T09:00:00.000Z' ``` -------------------------------- ### Initialize Property with Default Value and Transformer (TypeScript) Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The `initialize: true` option within `@MapField` enables automatic property initialization. When the source field is missing or undefined, the property will be set to the value returned by its `transformer` function. This ensures properties always have a defined state, even if not explicitly provided in the input data. ```typescript import { MapClass, MapInterface, MapField } from 'mapper-factory'; @MapClass() class Configuration { @MapField({ initialize: true, transformer: () => 'production', reverser: (env) => env }) environment: string; @MapField({ initialize: true, transformer: () => false, reverser: (debug) => debug }) debugMode: boolean; apiEndpoint: string; } interface Configuration extends MapInterface {} const config = new Configuration().from({ apiEndpoint: 'https://api.example.com' }); console.log(config.environment); // 'production' (initialized) console.log(config.debugMode); // false (initialized) console.log(config.apiEndpoint); // 'https://api.example.com' const mapped = config.toMap(); console.log(mapped.environment); // 'production' ``` -------------------------------- ### Untitled No description -------------------------------- ### Check if All Instance Properties are Defined (TypeScript) Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The filled() method checks if all properties of an instance have a defined value (not undefined or null). It returns true only if every property has been assigned a value. This is helpful for validation purposes, ensuring all required data is present. ```typescript import { MapClass, MapInterface } from 'mapper-factory'; @MapClass() class Credentials { username: string; password: string; apiKey: string; } interface Credentials extends MapInterface {} const partialCreds = new Credentials().from({ username: 'admin', password: 'secret' }); console.log(partialCreds.filled()); // false (apiKey is undefined) const completeCreds = new Credentials().from({ username: 'admin', password: 'secret', apiKey: 'xyz-789' }); console.log(completeCreds.filled()); // true (all properties defined) ``` -------------------------------- ### Untitled No description -------------------------------- ### Set Property Value with Nested Path (TypeScript) Source: https://context7.com/lucaangrisani/mapper-factory/llms.txt The set() method allows modification of a property value using a string path, which can navigate through nested objects and array indices. It automatically creates intermediate objects if they do not exist. This is useful for updating deeply nested data structures within mapped class instances. ```typescript import { MapClass, MapInterface, ArrayField } from 'mapper-factory'; @MapClass() class Task { title: string; status: string; } interface Task extends MapInterface {} @MapClass() class Project { name: string; @ArrayField(Task) tasks: Task[]; } interface Project extends MapInterface {} const project = new Project().from({ name: 'Website Redesign', tasks: [ { title: 'Design mockups', status: 'in-progress' }, { title: 'Implement frontend', status: 'pending' } ] }); project.set('tasks[1].status', 'in-progress'); console.log(project.get('tasks[1].status')); // 'in-progress' project.set('name', 'Website Redesign v2'); console.log(project.name); // 'Website Redesign v2' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.