### Install @type-ddd/cnpj Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/cnpj/README.md Install the library using npm or yarn. Ensure rich-domain is also installed. ```sh npm i rich-domain @type-ddd/cnpj # OR yarn add rich-domain @type-ddd/cnpj ``` -------------------------------- ### Install @type-ddd/cpf Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/cpf/README.md Commands to install the library using npm or yarn. ```sh npm i rich-domain @type-ddd/cpf # OR yarn add rich-domain @type-ddd/cpf ``` -------------------------------- ### Install @type-ddd/date Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/date/README.md Commands to install the library using npm or yarn. ```sh npm i rich-domain @type-ddd/date # OR yarn add rich-domain @type-ddd/date ``` -------------------------------- ### Install @type-ddd/phone Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/phone/README.md Commands to install the library using npm or yarn. ```sh npm i rich-domain @type-ddd/phone # OR yarn add rich-domain @type-ddd/phone ``` -------------------------------- ### Install @type-ddd/core with npm Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Install the full @type-ddd/core package using npm. This command installs all available packages. ```sh npm i @type-ddd/core ``` -------------------------------- ### Install @type-ddd/username Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/username/README.md Install the library along with its peer dependency rich-domain using npm or yarn. ```sh npm i rich-domain @type-ddd/username # OR yarn add rich-domain @type-ddd/username ``` -------------------------------- ### Install @type-ddd/email Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/email/README.md Installation commands for the package using npm or yarn. ```sh npm i rich-domain @type-ddd/email #OR yarn add rich-domain @type-ddd/email ``` -------------------------------- ### Install @type-ddd/core with yarn Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Install the full @type-ddd/core package using yarn. This command installs all available packages. ```sh yarn add @type-ddd/core ``` -------------------------------- ### Install @type-ddd/zip-code Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/zip-code/README.md Install the necessary packages using npm or yarn. ```sh npm i rich-domain @type-ddd/zip-code # OR yarn add rich-domain @type-ddd/zip-code ``` -------------------------------- ### Install @type-ddd/password and bcrypt Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/password/README.md Install the necessary packages using npm or yarn. Ensure bcrypt is installed for password encryption. ```sh npm i rich-domain @type-ddd/password bcrypt ``` ```sh yarn add rich-domain @type-ddd/password bcrypt ``` -------------------------------- ### Install @type-ddd/money Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/money/README.md Install the rich-domain and @type-ddd/money packages using npm or yarn. ```sh npm i rich-domain @type-ddd/money ``` ```sh yarn add rich-domain @type-ddd/money ``` -------------------------------- ### Install @type-ddd/core dependencies Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/type-ddd/README.md Use these commands to install the core library and the rich-domain dependency via npm or yarn. ```sh npm i rich-domain @type-ddd/core # OR yarn add rich-domain @type-ddd/core ``` -------------------------------- ### Install Type DDD Packages Source: https://context7.com/4lessandrodev/type-ddd/llms.txt Install the complete Type DDD core package or individual modules like CPF, email, password, money, and date. ```bash npm install @type-ddd/core ``` ```bash npm install @type-ddd/cpf npm install @type-ddd/email npm install @type-ddd/password npm install @type-ddd/money npm install @type-ddd/date ``` -------------------------------- ### Usage Example: Instantiate and Manipulate Payment Entity Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Demonstrates how to create a Payment entity instance using a factory method and apply business rules like fees and discounts. Shows how to extract the plain object representation from the domain entity. ```typescript // operation result const total = Money.create(500).value() as Money; const discount = Money.zero(); const fees = Money.zero(); // create a payment const payment = Payment.create({ total, discount, fees }).value() as Payment; // create fee and discount const fee = Money.create(17.50).value(); const disc = Money.create(170.50).value(); // apply fee and discount const result = payment.applyFees(fee).applyDiscount(disc); // get object from domain entity console.log(result.toObject()); { "id": "d7fc98f5-9711-4ad8-aa16-70cb8a52244a", "total": { "amount": 347 }, "discount": { "amount": 170.50 }, "fees": { "amount": 17.50 }, "createdAt":"2023-01-30T23:11:17.815Z", "updatedAt":"2023-01-30T23:11:17.815Z" } ``` -------------------------------- ### Usage Example for Money Value Object Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Demonstrates how to create, use, and perform operations with the Money value object instance, including checking operation results and accessing values. ```typescript // operation result const resA = Money.create(500); // check if provided a valid value console.log(resA.isOk()); // > true // money instance const moneyA = resA.value() as Money; moneyA.get("amount"); // 500 // using methods moneyA.isGt(Money.zero()); // > true const moneyB = Money.create(100).value() as Money; const moneyC = moneyA.sum(moneyB); const value = moneyC.get('amount'); console.log(value); // > 600 ``` -------------------------------- ### Use Dates class for date operations Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/date/README.md Examples of validating, initializing, manipulating, and formatting dates using the Dates class. ```ts import { Dates } from '@type-ddd/dates'; // Check if is valid value const isValid = Dates.isValid('2020-02-31'); // false // Initialize Dates instance with current date and time const date = Dates.init(); // OR // Create Dates instance from provided date or timestamp const result = Dates.create('2024-05-24'); // Add days, months, hours, minutes, weeks, or years const newDate = date.addDays(5).addMonths(2); // Format date according to various patterns const formattedDate = date.format('DD/MM/YYYY hh:mm:ss'); // Check if date is weekday or weekend const isWeekday = date.isWeekday(); const isWeekend = date.isWeekend(); ``` -------------------------------- ### Use PasswordValueObject for Password Management Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates the usage of `PasswordValueObject` for creating, encrypting, and comparing passwords. It includes examples for checking strength, encryption, and matching. ```typescript const passOrError = PasswordValueObject.create('my-strength-pass'); console.log(passOrError.isOk()); > true const pass = passOrError.value(); pass.encrypt(); console.log(pass.value()); > "$2a$12$AdLoTarjC5wnc1tAUc3j1.RczGxxImH0mG6dZkS5zPaGrTi/EmPWG" console.log(pass.isEncrypted()); > true const passMatch = pass.compare('my-strength-pass'); console.log(passMatch); > true console.log(PasswordValueObject.random(12).value()); > "WtS65$@!A6by" ``` -------------------------------- ### Void Success Result Example Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Shows a simple success case for a Result that returns void, indicating completion without a specific payload. ```typescript const checkEven = (value: number): Result => { const isPair = value % 2 === 0; // success case if(isPair) return Ok(); // failure case return Fail('not enven'); } ``` -------------------------------- ### Convert Result to Object Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Shows how to use the toObject method to get a summarized object representation of the Result instance, including its state and data. ```typescript console.log(result.toObject()); > Object `{ "data": null, "error": "not even", "isFail": true, "isOk": false, "metaData": Object {} } ` ``` -------------------------------- ### Initialize and Create Password Instances Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/password/README.md Demonstrates how to initialize a Password instance with a valid value or create one from a provided string. Also shows how to generate a random password. ```ts import { Password } from '@type-ddd/password'; // Initialize Password instance with a valid value const password = Password.init('Y8237FNB@'); // OR // Create Password instance from provided value const result = Password.create('Y8237FNB@'); // Or create a strong password const pass = Password.random(); ``` -------------------------------- ### Initialize Phone Instances Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/phone/README.md Create phone instances using init or the Result pattern via create. ```ts import { Phone } from '@type-ddd/phone' // Instance of phone or throws an error if provide an invalid value const phone = Phone.init('11994882021'); // OR // Result of phone (Check Result pattern docs) const result = Phone.create('11994882021'); result.isOk(); // true // phone instance or null if provide an invalid value const phone = result.value(); ``` -------------------------------- ### Initialize types-ddd Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/patterns/README.md Import the library to begin using its functionality. ```javascript const typesDdd = require('types-ddd'); // TODO: DEMONSTRATE API ``` -------------------------------- ### Initialize CNPJ Instance Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/cnpj/README.md Create a CNPJ instance using `init` for direct initialization or `create` for a result-based approach. Invalid values will cause an error or return a failed result. ```ts import { CNPJ } from '@type-ddd/cnpj' // Instance of CNPJ or throws an error if provide an invalid value const cnpj = CNPJ.init('54097792000193'); // OR // Result of CNPJ (Check Result pattern docs) const result = CNPJ.create('54097792000193'); result.isOk(); // true // cnpj instance or null if provide an invalid value const cnpj = result.value(); ``` -------------------------------- ### Initialize and Use Money Objects Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/money/README.md Demonstrates various ways to initialize Money objects and perform common monetary operations like sum, subtract, multiply, and divide. Ensure Money is imported from '@type-ddd/money'. ```typescript import { Money } from '@type-ddd/money' // Initialize a Money object with the provided value const amount = Money.init(100); // OR const result = Money.create(100); ``` ```typescript // Check if a value is a valid monetary amount const isValid = Money.isValid(100); ``` ```typescript // Sum two monetary values or Money objects const total = Money.sum(amount, 50); ``` ```typescript // Subtract one monetary value or Money object from another const difference = Money.subtract(total, 25); ``` ```typescript // Multiply two monetary values or Money objects const product = Money.multiply(difference, 2); ``` ```typescript // Divide one monetary value or Money object by another const quotient = Money.divide(product, 4); ``` ```typescript // Round down the monetary value to the nearest integer const floorValue = quotient.floor(); ``` ```typescript // Round up the monetary value to the nearest integer const ceilValue = quotient.ceil(); ``` ```typescript // Calculate compound interest based on the provided rate and periods const interest = Money.compoundInterest(5, 10); ``` ```typescript // Generate a random monetary value within the specified range const randomAmount = Money.random(10, 100); ``` ```typescript // Calculate the average value among the provided Money objects const average = Money.average([amount, total, difference]); ``` ```typescript // Convert the current Money value to another currency using the provided exchange rate const convertedAmount = amount.convertTo(2); ``` ```typescript // Generate a formatted string representing the monetary value in a specific currency and locale const formattedAmount = amount.coin('USD', 'en-US'); console.log(formattedAmount); // Output: $100.00 (assuming 100 is the amount in USD) ``` -------------------------------- ### Implement Data Adapters Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Shows how to create adapters for transforming data between the domain layer and the data layer (persistence). Use `IAdapter` to define conversion logic. ```typescript // from domain to data layer class MyAdapterToInfra implements IAdapter{ build(target: DomainUser): Result { // ... } } // from data layer to domain class MyAdapterToDomain implements IAdapter{ build(target: DataUser): Result { // ... } } // You can use adapter instance in toObject function const myAdapter = new MyAdapterToInfra(); const dataUser = domainUser.toObject(myAdapter); ``` -------------------------------- ### Initialize CPF instances Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/cpf/README.md Create CPF instances or result objects. Invalid values will throw an error or return a failure result. ```ts import { CPF } from '@type-ddd/cpf' // Instance of cpf or throws an error if provide an invalid value const cpf = CPF.init('54097792000193'); // OR // Result of cpf (Check Result pattern docs) const result = CPF.create('54097792000193'); result.isOk(); // true // cpf instance or null if provide an invalid value const cpf = result.value(); ``` -------------------------------- ### Create and Convert Weight Value Object Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates creating a WeightValueObject with a value and unit, checking its validity, and converting it to kilograms. Ensure WeightValueObject is imported. ```typescript const result = WeightValueObject.create({ value: 1000, unit: "TON" }); console.log(result.isOk()); > true const weight = result.value(); console.log(weight.unit); > "TON" console.log(weight.weight.value()); > 1000 // Convert instance value and unit to KG weight.toKG(); console.log(weight.unit); > "KG" console.log(weight.weight.value()); > 1 ``` -------------------------------- ### Encrypt and Compare Passwords Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/password/README.md Shows how to encrypt a password and then compare it against plain text to verify equality. Use the `isEncrypted()` method to check the current state. ```ts const password = Password.init('#$89ABC_v'); // check if password is encrypted password.isEncrypted(); // false const encrypted = password.encrypt(); // compare encrypted.compare('#$89ABC_v'); // true ``` -------------------------------- ### Initialize ZipCode Instance Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/zip-code/README.md Use ZipCode.init to create an instance, which throws an error for invalid values. Alternatively, use ZipCode.create for a Result pattern, allowing checks before accessing the value. ```ts import { ZipCode } from '@type-ddd/zip-code' // Instance of zipCode or throws an error if provide an invalid value const zipCode = ZipCode.init('75520140'); // OR // Result of zipCode (Check Result pattern docs) const result = ZipCode.create('75520140'); result.isOk(); // true // zipCode instance or null if provide an invalid value const zipCode = result.value(); ``` -------------------------------- ### Add and Dispatch Domain Event Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates how to add a domain event to a product instance and then dispatch it. Events are stored in memory and cleared after dispatch. ```typescript const result = Product.create({ name, price }); const product = result.value(); const event = new ProductCreatedEvent(); product.addEvent(event); ``` ```typescript product.dispatch("ProductCreated"); > "EVENT DISPATCH: [Aggregate@Product]:6039756f-d3bc-452e-932a-ec89ff536dda" ``` -------------------------------- ### Display Folder Structure Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Shows a suggested folder structure for domain-rich applications using types-ddd. ```shell $ tree . ├── package.json ├── README.md └── src ├── configs │ └── env ├── shared │ └── infra │ └── server └── modules │ │ └── [module-name] │ │ ├── domain │ ├── value-objects │ ├── entities │ ├── aggregates │ ├── events │ ├── subscriptions │ ├── adapter │ ├── repository-interface │ └── domain-services │ │ ├── application │ └── use-cases │ │ └── infra ├── models └── repository ``` -------------------------------- ### Require types-ddd Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/logger/README.md Demonstrates how to import the types-ddd library in a Node.js environment. ```javascript const typesDdd = require('types-ddd'); ``` -------------------------------- ### Instantiate and Access Value Object Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Use the create method to generate an instance and verify the result before accessing internal values. ```ts const result = Name.create('Jane'); console.log(result.isOk()); > true const name = result.value(); console.log(name.get('value')); > "Jane" ``` -------------------------------- ### Manage Aggregate Domain Events Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Shows how to register and dispatch events directly from an aggregate instance. ```ts order.addEvent('Event', (...args) => { console.log(args); }); // Or add an EventHandler instance order.addEvent(new OrderCreatedEvent()); order.dispatchEvent('OrderBegun'); // dispatch with args order.dispatchEvent('Event', { info: 'custom_args' }); // OR call all added events await order.dispatchAll(); ``` -------------------------------- ### Create and Handle Zip Codes Source: https://context7.com/4lessandrodev/type-ddd/llms.txt Use ZipCode.create for creating zip codes with validation. Access the raw numeric value and formatted pattern. ZipCode.init can be used when invalid input should throw an error. ```typescript import { ZipCode } from '@type-ddd/zip-code'; // Create zip code const result = ZipCode.create('75520-140'); if (result.isOk()) { const zipCode = result.value(); console.log(zipCode.value()); // "75520140" (only numbers) console.log(zipCode.toPattern()); // "75520-140" } // Validation console.log(ZipCode.isValid('75520140')); // true console.log(ZipCode.isValid('75520-140')); // true console.log(ZipCode.isValid('123')); // false // Static utilities console.log(ZipCode.addMask('75520140')); // "75520-140" console.log(ZipCode.removeSpecialChars('75520-140')); // "75520140" // Init (throws on invalid) const zipCode = ZipCode.init('01310-100'); console.log(zipCode.value()); // "01310100" ``` -------------------------------- ### Create and Format Date Value Object Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates creating a DateValueObject from a Date object, formatting it, and performing date arithmetic. Ensure the DateValueObject is imported before use. ```typescript const currentDate = new Date(); const myDate = DateValueObject.create(currentDate).value(); console.log(myDate.value()); > "2021-10-11T14:45:04.758Z" console.log(myDate.format("DD-MM-YYYY")); > "11-10-2021" myDate.addDays(3); console.log(myDate.value()); > "2021-10-14T14:45:04.758Z" const isWeekend = myDate.isWeekend(); console.log(isWeekend); > false myDate.addHours(7); const isAfter = myDate.isAfter(currentDate); console.log(isAfter); > true ``` -------------------------------- ### Create Ok and Fail Results Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates creating success (Ok) and failure (Fail) results using imported functions. Supports optional payload and error messages. ```typescript import { Ok, Fail } from 'types-ddd'; // Success use case return Ok(); // OR return Ok('success message'); // Failure use case return Fail('error message here'); ``` -------------------------------- ### Implement Event Handlers Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Demonstrates creating a custom event handler class by extending the EventHandler base class. ```ts import { Context, EventHandler } from '@type-ddd/core'; class OrderCreatedEvent extends EventHandler { constructor() { super({ eventName: 'OrderCreated' }); } dispatch(order: Order): void { // dispatch event to another context order.context().dispatchEvent('Context:Event', order.toObject()); }; } ``` -------------------------------- ### Initialize and Use Email Class Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/email/README.md Basic usage for validating email strings and extracting nickname and domain parts. ```ts import { Email } from '@type-ddd/email'; // Check if is valid value const isValid = Email.isValid('sample@domain.com'); // true // Initialize Email instance with a valid email address const email = Email.init('example@example.com'); // OR // Create Email instance from provided email address const result = Email.create('example@example.com'); // Get parts of the email address const nickname = email.nick(); const domain = email.domain(); ``` -------------------------------- ### Create and Manipulate Currency Value Object Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Shows how to create a CurrencyValueObject with a specified currency and value, and perform arithmetic operations. Import CurrencyValueObject before use. ```typescript const voOrErr = CurrencyValueObject.create({ currency: 'BRL', value: 0.50 }); const myCurrency = voOrErr.value(); console.log(myCurrency.value()); > 0.5 myCurrency.add(0.50); // 1 myCurrency.multiplyBy(50); // 50 myCurrency.divideBy(2); // 25 myCurrency.subtractBy(5); // 20 myCurrency.add(80); // 100 myCurrency.addPercent(2); // 102 myCurrency.subtractBy(2); // 100 myCurrency.subtractPercent(30); // 70 console.log(myCurrency.value()); > 70 console.log(myCurrency.getCoin()); > "R$ 70.00" // OR chain const result = myCurrency.add(10).addPercent(21).multiplyBy(3).subtractBy(50); ``` -------------------------------- ### Create Payment Entity with Business Rules Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Define a Payment entity with methods to apply fees and discounts, encapsulating business logic. Use the static `create` method for instantiation, which returns a Result type. ```typescript import { Entity, Ok, Fail, Result, UID } from '@type-ddd/core'; interface Props { id?: UID; total: Money; discount: Money; fees: Money; } // simple example as payment entity using money value object export default class Payment extends Entity { // private constructor private constructor(props: Props){ super(props); } // any business rule behavior. Update total. public applyFees(fees: Money): Payment { const props = this.props; const total = props.total.sum(fees); return new Payment({ ...props, total, fees }); } // any business rule behavior. Discount must be less or equal total. public applyDiscount(discount: Money): Payment { const props = this.props; const total = props.total.subtract(discount); return new Payment({ ...props, total, discount }); } // factory method to create a instance. Value must be positive. public static create(props: Props): Result { return Ok(new Payment(props)); } } ``` -------------------------------- ### Create and Extract Name Information Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates creating a UserNameValueObject from a full name string and extracting first, middle, last names, and initials. Ensure UserNameValueObject is imported. ```typescript const result = UserNameValueObject.create('jannie lan spark'); console.log(result.isOk()); > true const name = result.value(); console.log(name.value()); > "Jannie Lan Spark" console.log(name.getLastName()); > "Spark" console.log(name.getMiddleName()); > "Lan" console.log(name.getFirstName()); > "Jannie" console.log(name.getInitials()); > "J.L.S" ``` -------------------------------- ### Initialize UserName Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/username/README.md Create a UserName instance directly or via the Result pattern to handle validation errors. ```ts import { UserName } from '@type-ddd/username' // Instance of name or throws an error if provide an invalid value const name = UserName.init('jane doe'); // OR // Result of name (Check Result pattern docs) const result = UserName.create('jane doe'); result.isOk(); // true // userName instance or null if provide an invalid value const name = result.value(); ``` -------------------------------- ### Password Validation and Encryption with Bcrypt Source: https://context7.com/4lessandrodev/type-ddd/llms.txt Use this snippet to create, validate, encrypt, and compare passwords. Customize length requirements by setting Password.MIN_LENGTH, Password.MAX_LENGTH, and Password.MESSAGE. ```typescript import { Password } from '@type-ddd/password'; // Create password (min 5, max 22 chars by default) const result = Password.create('my-secure-pass'); if (result.isOk()) { const password = result.value(); console.log(password.value()); // "my-secure-pass" console.log(password.isEncrypted()); // false // Encrypt password const encrypted = password.encrypt(); console.log(encrypted.isEncrypted()); // true console.log(encrypted.value()); // "$2b$10$" // Compare passwords console.log(encrypted.compare('my-secure-pass')); // true console.log(encrypted.compare('wrong-pass')); // false } // Generate random password const randomPassword = Password.random(12); console.log(randomPassword.value()); // e.g., "WtS65$@!A6by" // Check if value is encrypted console.log(Password.isEncrypted('$2b$10$...')); // true console.log(Password.isEncrypted('plain-text')); // false // Customize password length requirements Reflect.set(Password, 'MIN_LENGTH', 8); Reflect.set(Password, 'MAX_LENGTH', 32); Reflect.set(Password, 'MESSAGE', 'Password must be 8-32 characters'); ``` -------------------------------- ### Create and Handle Phone Numbers Source: https://context7.com/4lessandrodev/type-ddd/llms.txt Use Phone.create to handle universal phone numbers, automatically detecting mobile or landline. Access formatted values, call details, and DDD information. Use MobilePhone.create for direct mobile number instantiation. ```typescript import { Phone, MobilePhone, HomePhone } from '@type-ddd/phone'; // Universal phone handling (auto-detects mobile vs landline) const mobileResult = Phone.create('(11) 99876-5432'); if (mobileResult.isOk()) { const phone = mobileResult.value(); console.log(phone.value()); // "11998765432" console.log(phone.toPattern()); // "(11) 99876-5432" console.log(phone.toCall()); // "011998765432" console.log(phone.number()); // "998765432" console.log(phone.code()); // 11 (DDD) console.log(phone.uf()); // "SP" (state from DDD) console.log(phone.isMobile()); // true console.log(phone.isHome()); // false } // Landline phone const homeResult = Phone.create('(11) 3456-7890'); if (homeResult.isOk()) { const phone = homeResult.value(); console.log(phone.isMobile()); // false console.log(phone.isHome()); // true } // Direct mobile phone creation const mobile = MobilePhone.create('11987654321'); if (mobile.isOk()) { console.log(mobile.value().toPattern()); // "(11) 98765-4321" } ``` -------------------------------- ### Create and Extract Email Information Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Shows how to create an EmailValueObject from a string and extract the local part and domain. Import EmailValueObject before use. ```typescript const result = EmailValueObject.create('dany@mailer.com'); console.log(result.isOk()); > true const email = result.value(); console.log(email.value()); > "dany@mailer.com" console.log(email.getNick()); > "dany" console.log(email.getDomain()); > "mailer.com" ``` -------------------------------- ### Basic Logger Usage Source: https://context7.com/4lessandrodev/type-ddd/llms.txt Use Logger.info, Logger.warn, and Logger.error for basic logging. Logs are disabled in production by default unless specific environment variables are set. ```typescript import { Logger } from '@type-ddd/logger'; // Basic logging (disabled in production by default) Logger.info('Application started'); Logger.warn('Configuration missing, using defaults'); Logger.error('Failed to connect to database'); ``` -------------------------------- ### Define a Simple Value Object Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Create a basic Value Object by extending the ValueObject class and implementing a static create method. ```ts import { IResult, Result, ValueObject } from "types-ddd"; export interface NameProps { value: string; } export class Name extends ValueObject{ private constructor(props: NameProps) { super(props); } public static create(value: string): IResult { return Ok(new Name({ value })); } } export default Name; ``` -------------------------------- ### Configure PasswordValueObject Constraints Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Shows how to customize the minimum and maximum length, as well as the error message for `PasswordValueObject` using `Reflect.set`. ```typescript Reflect.set(PasswordValueObject, "MIN_LENGTH", 10); Reflect.set(PasswordValueObject, "MAX_LENGTH", 20); Reflect.set(PasswordValueObject, "MESSAGE", "Password must be between 10 and 20 characters"); ``` -------------------------------- ### Test Value Object Instance and Validation Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates creating a Value Object instance and testing its validation logic. Values are not modified if they fail validation. ```typescript const result = Name.create('Jane'); console.log(result.isOk()); > true const name = result.value(); console.log(name.get('value')); > "Jane" const empty = ''; name.set('value').to(empty); console.log(name.get('value')); > "Jane" name.set('value').to("Jack"); console.log(name.get('value')); > "Jack" ``` -------------------------------- ### Create a Money Value Object with Business Rules Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Defines a Money value object with methods for validation, calculation, and comparison. It uses a private constructor and static factory methods for instantiation and validation. ```typescript import { ValueObject, Ok, Fail, Result } from '@type-ddd/core'; interface Props { amount: number; } // simple example as monetary value object business behavior export default class Money extends ValueObject { // private constructor. Avoid public new. private constructor(props: Props) { super(props); } // any business rule behavior. Check. public isGt(x: Money): boolean { const { number: Check } = this.validator; const xValue = x.get('amount'); const currentValue = this.get('amount'); return Check(xValue).isGreaterThan(currentValue); } // any business rule behavior. Calc. public sum(x: Money): Money { const { number: Calc } = this.util; const value = x.get('amount'); const current = this.get('amount'); const amount = Calc(current).sum(value); return new Money({ amount }); } // any business rule behavior. Calc. public subtract(x: Money): Money { const { number: Calc } = this.util; const value = x.get('amount'); const current = this.get('amount'); const amount = Calc(current).subtract(value); return new Money({ amount }); } // any business rule to validate state. public static isValidProps({ amount }: Props): boolean { const { number: Check } = this.validator; return Check(amount).isPositive(); } // shortcut to create a zero value public static zero(): Money { return new Money({ amount: 0 }); } // factory method to create an instance and validate value. public static create(amount: number): Result { const isValid = this.isValidProps({ amount }); if(!isValid) return Fail("Invalid amount for money"); return Ok(new Money({ amount })); } } ``` -------------------------------- ### Create Multiple Value Objects Efficiently Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Utilize the static 'createMany' method to instantiate multiple Value Objects, Entities, or Aggregates from an array of configurations. It returns both the created instances and a result object to check for overall success. ```typescript const itemPrice = Class(ProductPrice, { value: price }); const itemName = Class(ProductName, { value: name }); const itemQtd = Class(ProductQtd, { value: qtd }); const { data, result } = ValueObject.createMany([ itemPrice, itemName, itemQtd ]); // you check if all value objects are ok if (result.isFail()) return Result.fail(result.error()); // you can get instances from iterator data. In the same order as the array const price = data.next().value() as ProductPrice; // index 0 const name = data.next().value() as ProductName; // index 1 const quantity = data.next().value() as ProductQtd; // index 2 const product = Product.create({ name, price, quantity }); ``` -------------------------------- ### Using Void Success Result Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates checking the status of a void Result and verifying that it is successful and has no value or error. ```typescript const result: Result = checkEven(42); console.log(result.isOk()); > true console.log(result.isFail()); > false console.log(result.error()); > null console.log(result.value()); > null console.log(result.metaData()); > 'Object {}' ``` -------------------------------- ### Define ID Type Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates usage of the UID type definition. ```ts import { UID, ID } from 'types-ddd'; // UID type let id: UID; // ID value id = ID.create(); ``` -------------------------------- ### Define a Simple Entity Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Create an entity by extending the base Entity class and implementing a static create method. ```typescript interface UserProps { id?: UID, name: Name, age: Age }; export class User extends Entity{ private constructor(props: UserProps){ super(props) } public static create(props: UserProps): IResult { return Result.Ok(new User(props)); } } export default User; ``` -------------------------------- ### Execute Result Hooks Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Executes a command based on the Result state. Requires an implementation of ICommand. ```ts class Command implements ICommand { execute(): void { console.log("running command ..."); } } const myCommand = new Command(); const result = Result.Ok(); result.execute(myCommand).on('Ok'); ``` ```ts class Command implements ICommand { execute(error: string): void { console.log(error); } } const myCommand = new Command(); const result = Result.fail('something went wrong'); result.execute(myCommand).withData(result.error()).on('fail'); ``` -------------------------------- ### Initialize Entity with Value Objects Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Combine validated value objects before passing them to the entity creation method. ```typescript const nameAttr = Name.create('James'); const ageAttr = Age.create(21); // always check if value objects are success const voResult = Combine([ nameAttr, ageAttr ]) console.log(voResult.isOk()); > true const name = nameAttr.value(); const age = ageAttr.value(); // if you don't provide a value for the id it will be generated automatically const result = User.create({ name, age }); console.log(result.isOk()); > true ``` -------------------------------- ### UserName Utility Methods Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/username/README.md Perform common string manipulations and extractions on a UserName instance. ```ts const fullName = UserName.init('jane doe spencer') const initials = fullName.initials(); // JDS const middle = fullName.middleName(); // Doe const first = fullName.firstName(); // Jane const firstWithTitle = fullName.title('Sra.').firstName(); // Sra. Jane const last = fullName.lastName(); // Spencer const upper = fullName.upperCase(); // JANE DOE SPENCER ``` -------------------------------- ### Implement a ProductCreatedEvent Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Implements a domain event for product creation. This event can be dispatched to trigger actions when a product is created. ```typescript export class ProductCreatedEvent implements IHandle{ public eventName: string; constructor() { this.eventName = 'ProductCreated'; } dispatch(event: IDomainEvent): void { // your action here const { aggregate } = event; console.log(`EVENT DISPATCH: ${aggregate.hashCode().value()}`); } } export default ProductCreatedEvent; ``` -------------------------------- ### Compare ID Instances Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Checks equality between two ID instances. ```ts const idA = ID.short('this-is-my-id-01'); const idB = ID.short('this-is-my-id-02'); console.log(idA.equal(idB)); console.log(idB.equal(idB)); ``` -------------------------------- ### Format CPF with mask Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/cpf/README.md Apply CPF masking to an existing instance or a raw string. ```ts cpf.toPattern(); // Output: 54.097.792/0001-93 ``` ```ts CPF.addMask('54097792000193'); // Output: 54.097.792/0001-93 ``` -------------------------------- ### Subscribe to Global Events Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Utilizes the global Context to subscribe to and dispatch events across different contexts using wildcard patterns. ```ts import { Context } from '@type-ddd/core'; const context = Context.events(); context.subscribe('Context:Event', (event) => { const [model] = event.detail; console.log(model); }); // dispatch an event to a context with args context.dispatchEvent('Context:Event', { name: 'Jane' }); // Dispatching events to specific contexts // Dispatches the SIGNUP event to Context-X context.dispatchEvent('Context-X:Signup'); // Dispatches the SIGNUP event to all contexts context.dispatchEvent('*:Signup'); // Dispatches all events to all contexts. Not recommended context.dispatchEvent('*:*'); // Dispatches all events under Context-Y context.dispatchEvent('Context-Y:*'); ``` -------------------------------- ### Handle user names with UserName Value Object Source: https://context7.com/4lessandrodev/type-ddd/llms.txt Provides methods for name parsing, case conversion, and validation. Length constraints can be modified via Reflect. ```typescript import { UserName } from '@type-ddd/username'; // Create username with auto-capitalization const result = UserName.create('john william doe'); if (result.isOk()) { const name = result.value(); console.log(name.value()); // "John William Doe" console.log(name.firstName()); // "John" console.log(name.middleName()); // "William" console.log(name.lastName()); // "Doe" console.log(name.hasMiddleName()); // true console.log(name.hasLastName()); // true // Case conversions console.log(name.upperCase()); // "JOHN WILLIAM DOE" console.log(name.lowerCase()); // "john william doe" // Initials console.log(name.initials()); // "JWD" console.log(name.initials('.')); // "J.W.D" // With title const titled = name.title('Dr.'); console.log(titled.fullName()); // "Dr. John William Doe" console.log(titled.firstName()); // "Dr. John" console.log(titled.lastName()); // "Dr. Doe" } // Static capitalization console.log(UserName.capitalize('jane marie smith')); // "Jane Marie Smith" // Validation (2-82 chars by default) console.log(UserName.isValid('Jo')); // true console.log(UserName.isValid('J')); // false (too short) // Customize length constraints Reflect.set(UserName, 'MIN_LENGTH', 3); Reflect.set(UserName, 'MAX_LENGTH', 50); ``` -------------------------------- ### Apply Mask to ZipCode String Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/zip-code/README.md Use the ZipCode.addMask static method to apply a standard mask to a raw ZipCode string. ```ts ZipCode.addMask('75520140'); // Output: 75520-140 ``` -------------------------------- ### Create an Aggregate for Domain Context Source: https://github.com/4lessandrodev/type-ddd/blob/main/README.md Defines an Order aggregate that encapsulates entities and value objects, utilizing static factory methods and internal event registration. ```ts import { Aggregate, Ok, Fail, Result, UID, EventHandler } from '@type-ddd/core'; // Entities and VO that encapsulate context. interface Props { id?: UID; payment: Payment; items: List; status: OrderStatus; customer: Customer; } // Simple example of an order aggregate encapsulating entities and // value objects for context. export default class Order extends Aggregate { // Private constructor to ensure instances creation through static methods. private constructor(props: Props){ super(props); } // Static method to begin a new order. // Takes a customer as parameter and returns an instance of Order. public static begin(customer: Customer): Order { // Initialize the status of the order as "begin". const status = OrderStatus.begin(); // Initialize the list of items as empty. const items: List = List.empty(); // Initialize the payment as zero, since the order hasn't been paid yet. const payment = Payment.none(); // Create a new instance of Order with the provided parameters. const order = new Order({ status, payment, items, customer }); // Add an event to indicate that the order has begun. order.addEvent('ORDER_HAS_BEGUN', (order) => { // Perform some important operation when the order begins. console.log('Do something important...'); }); // Alternatively, add an event by creating an // instance of a class that extends EventHandler. order.addEvent(new OrderBeganEventHandler()); // Return the created order instance. return order; } // Method to add an item to the order. // Takes an item as parameter and returns the Order instance. addItem(item: Item): Order { // Add the item to the order's items list. this.props.items.add(item); // Sum item price to payment amount this.props.payment.sum(item.price); // Return the Order instance itself to allow chained calls. return this; } // Method to perform the payment of the order. // Takes a payment object as parameter. pay(payment: Payment): Order { // Set the status of the order to "paid". this.props.status = OrderStatus.paid(); // Set the provided payment object. this.props.payment = payment; // Add an event to indicate that the order has been paid. // Assuming OrderPaidEvent is a class representing // the event of order payment. this.addEvent(new OrderPaidEventHandler()); return this; } // Static method to create an instance of Order. // Returns a Result, which can be Ok (success) or Fail (failure). // The value of the Result is an instance of Order, // if creation is successful. public static create(props: Props): Result { return Ok(new Order(props)); } } ``` -------------------------------- ### Format ZipCode with Mask Source: https://github.com/4lessandrodev/type-ddd/blob/main/packages/zip-code/README.md Apply a standard mask to a ZipCode instance using the toPattern method. This method returns the ZipCode with the mask applied. ```ts zipCode.toPattern(); // Output: 75520-140 ``` -------------------------------- ### Check Result Success Case Source: https://github.com/4lessandrodev/type-ddd/blob/main/docs/README.md Demonstrates how to check if a Result is successful and access its value and metadata. ```typescript const result = isEven(42); console.log(result.isOk()); > true console.log(result.value()); > 'Object { data: "42 is even" }' console.log(result.metaData()); > 'Object { arg: 42 }' console.log(result.error()); > null ``` -------------------------------- ### Configure Logger Environment Source: https://context7.com/4lessandrodev/type-ddd/llms.txt Control logger output using environment variables. Set NODE_ENV=production to disable logs, TYPES_DDD_LOGS=off to disable all logs, or TYPES_DDD_LOGS=error to only show errors. ```typescript // Environment configuration // Set NODE_ENV=production to disable logs // Set TYPES_DDD_LOGS=off to disable all logs // Set TYPES_DDD_LOGS=error to only show errors process.env.NODE_ENV = 'development'; Logger.info('This will be logged'); process.env.NODE_ENV = 'production'; Logger.info('This will NOT be logged'); process.env.TYPES_DDD_LOGS = 'error'; Logger.error('This WILL be logged even in production'); Logger.info('This will NOT be logged'); ```