### Create Product and Order Item Source: https://github.com/brunomm/entity-base/blob/main/docs/documentacao-abrangente.md Demonstrates creating a Product entity with details like name, description, price, and stock. It then shows how to create an OrderItem associated with this product, specifying quantity and unit price. The example also includes validation for the OrderItem. ```javascript import { Product, OrderItem } from './marketplace_entities'; // Criando um produto const laptopProduct = new Product({ name: 'Laptop Gamer XYZ', description: 'Laptop de alta performance para jogos', price: 7500.00, stock: 10 }); console.log('Nome do Produto:', laptopProduct.name); // Laptop Gamer XYZ console.log('Preço do Produto:', laptopProduct.price); // 7500 // Criando um item de pedido para o produto const orderItem = new OrderItem({ product: laptopProduct, quantity: 2, unitPrice: laptopProduct.price // Pode ser diferente do preço atual do produto no momento da compra }); console.log('Item de Pedido - Produto:', orderItem.product.name); // Laptop Gamer XYZ console.log('Item de Pedido - Quantidade:', orderItem.quantity); // 2 console.log('Item de Pedido - Preço Unitário:', orderItem.unitPrice); // 7500 // Validando o item de pedido console.log('Item de Pedido válido?', orderItem.validate().isValid()); // true // Exemplo de validação falha para OrderItem const invalidOrderItem = new OrderItem({ quantity: 0 }); // Produto faltando e quantidade inválida console.log('Item de Pedido inválido?', invalidOrderItem.validate().isValid()); // false console.log('Erros:', invalidOrderItem.validate().errors.fullMessages()); // Saída esperada: [ 'Product é obrigatório', 'Quantity deve ser maior que zero' ] ``` -------------------------------- ### Basic Entity Example Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md A simple example of creating a `PersonEntity` subclass extending `EntityBase` with defined default attributes. ```javascript class PersonEntity extends EntityBase { static defaultAttributes = { name: '', age: 0 }; } ``` -------------------------------- ### Install EntityBase via npm Source: https://github.com/brunomm/entity-base/blob/main/README.md This command installs the EntityBase package version 1.0.0-beta using npm. It's a prerequisite for using EntityBase in your project. ```bash npm install --save @btec/entity-base@1.0.0-beta ``` -------------------------------- ### Create and Access Customer with Address using EntityBase Source: https://github.com/brunomm/entity-base/blob/main/docs/documentacao-abrangente.md Demonstrates creating a Customer entity with an associated Address entity. It shows how to instantiate these entities with data, access their attributes, and perform validation. The example also includes a scenario for an invalid customer to show how validation errors are reported. ```javascript import { Customer, Address } from './marketplace_entities'; // Criando um endereço const customerAddress = new Address({ street: 'Rua das Flores', number: '123', city: 'São Paulo', state: 'SP', zipCode: '01000-000' }); // Criando um cliente com o endereço const customer = new Customer({ name: 'João Silva', email: 'joao.silva@example.com', phone: '11987654321', address: customerAddress }); console.log('Nome do Cliente:', customer.name); // João Silva console.log('Email do Cliente:', customer.email); // joao.silva@example.com console.log('Rua do Cliente:', customer.address.street); // Rua das Flores console.log('Cidade do Cliente:', customer.address.city); // São Paulo // Validando o cliente const validatedCustomer = customer.validate(); console.log('Cliente válido?', validatedCustomer.isValid()); // true // Exemplo de validação falha const invalidCustomer = new Customer({ name: 'Maria' }); // Email e endereço faltando const validatedInvalidCustomer = invalidCustomer.validate(); console.log('Cliente válido?', validatedInvalidCustomer.isValid()); // false console.log('Erros:', validatedInvalidCustomer.errors.fullMessages()); // Saída esperada: [ 'Email é obrigatório', 'Address é obrigatório' ] ``` -------------------------------- ### Serialize Order for API with toParams() Source: https://github.com/brunomm/entity-base/blob/main/docs/documentacao-abrangente.md Shows how to convert an order object into a parameter-friendly format using the `toParams()` method, which is useful for sending order data to an API. The example includes the expected JSON output structure. ```javascript import { Customer, Address, Product, OrderItem, Payment, Order } from './marketplace_entities'; // ... (código para criar o pedido 'order' do Exemplo 3) // Para fins de exemplo, vamos recriar o pedido aqui: const customerAddress = new Address({ street: 'Av. Paulista', number: '1000', city: 'São Paulo', state: 'SP', zipCode: '01310-100' }); const customer = new Customer({ name: 'Ana Paula', email: 'ana.paula@example.com', address: customerAddress }); const productA = new Product({ name: 'Smartphone X', price: 3000, stock: 50 }); const productB = new Product({ name: 'Fone Bluetooth', price: 300, stock: 100 }); const item1 = new OrderItem({ product: productA, quantity: 1, unitPrice: productA.price }); const item2 = new OrderItem({ product: productB, quantity: 2, unitPrice: productB.price }); const payment = new Payment({ method: 'Credit Card', amount: (item1.quantity * item1.unitPrice) + (item2.quantity * item2.unitPrice), status: 'approved' }); const order = new Order({ customer: customer, items: [item1, item2], totalAmount: payment.amount, payment: payment, status: 'processing' }); const orderPayload = order.toParams(); console.log('Payload do Pedido para API:'); console.log(JSON.stringify(orderPayload, null, 2)); /* Saída esperada (simplificada): { "customer": { "name": "Ana Paula", "email": "ana.paula@example.com", "phone": "", "address": { "street": "Av. Paulista", "number": "1000", "complement": "", "neighborhood": "", "city": "São Paulo", "state": "SP", "zipCode": "01310-100" } }, "items": [ { "product": { "name": "Smartphone X", "description": "", "price": 3000, "stock": 50 }, "quantity": 1, "unitPrice": 3000 }, { "product": { "name": "Fone Bluetooth", "description": "", "price": 300, "stock": 100 }, "quantity": 2, "unitPrice": 300 } ], "totalAmount": 3600, "payment": { "method": "Credit Card", "amount": 3600, "status": "approved" }, "status": "processing" } */ ``` -------------------------------- ### Create Complete Order with Items and Payment Source: https://github.com/brunomm/entity-base/blob/main/docs/documentacao-abrangente.md Illustrates the process of building a complete order. This involves creating a Customer with an Address, defining multiple Products, creating OrderItems for each product, and setting up Payment details. Finally, it shows how to assemble these components into an Order entity and perform validation. ```javascript import { Customer, Address, Product, OrderItem, Payment, Order } from './marketplace_entities'; // 1. Criar Cliente e Endereço const customerAddress = new Address({ street: 'Av. Paulista', number: '1000', city: 'São Paulo', state: 'SP', zipCode: '01310-100' }); const customer = new Customer({ name: 'Ana Paula', email: 'ana.paula@example.com', address: customerAddress }); // 2. Criar Produtos const productA = new Product({ name: 'Smartphone X', price: 3000, stock: 50 }); const productB = new Product({ name: 'Fone Bluetooth', price: 300, stock: 100 }); // 3. Criar Itens de Pedido const item1 = new OrderItem({ product: productA, quantity: 1, unitPrice: productA.price }); const item2 = new OrderItem({ product: productB, quantity: 2, unitPrice: productB.price }); // 4. Criar Pagamento const payment = new Payment({ method: 'Credit Card', amount: (item1.quantity * item1.unitPrice) + (item2.quantity * item2.unitPrice), status: 'approved' }); // 5. Criar Pedido const order = new Order({ customer: customer, items: [item1, item2], // Passando um array, EntityBase converterá para Map totalAmount: payment.amount, payment: payment, status: 'processing' }); console.log('ID do Pedido:', order.idOrToken); // UUID gerado console.log('Cliente do Pedido:', order.customer.name); // Ana Paula console.log('Total do Pedido:', order.totalAmount); // 3600 console.log('Método de Pagamento:', order.payment.method); // Credit Card console.log('Status do Pedido:', order.status); // processing // Acessando itens do pedido (Map) console.log('Número de itens no pedido:', order.items.size); // 2 // Iterando sobre os itens do pedido order.array('items').forEach(item => { console.log(`- ${item.product.name} (x${item.quantity})`); }); // Saída esperada: // - Smartphone X (x1) // - Fone Bluetooth (x2) // Validando o pedido completo console.log('Pedido válido?', order.validate().isValid()); // true ``` -------------------------------- ### EntityBase Customization Example Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Illustrates how to extend the base EntityBase class to create a custom entity with overridden methods. This example shows how to customize the `toParams` method for specific serialization needs, including accessing related entities. ```javascript class CustomUserEntity extends UserEntity { toParams() { return { name: this.name, company_id: this.company?.id, car_ids: Array.from(this.cars.values()).map(c => c.id) }; } } ``` -------------------------------- ### Nested Relationships Example Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Demonstrates setting up and instantiating entities with nested `belongsTo` and `hasMany` relationships. ```javascript class CompanyEntity extends EntityBase { static defaultAttributes = { name: '' }; } class CarEntity extends EntityBase { static defaultAttributes = { model: '', price: 0 }; } class UserEntity extends EntityBase { static defaultAttributes = { name: '', company: null, cars: [] }; static belongsTo = { company: CompanyEntity }; static hasMany = { cars: CarEntity }; } const user = new UserEntity({ name: 'João', company: { name: 'Google' }, cars: [{ model: 'Tesla', price: 80000 }, { model: 'Civic', price: 40000 }] }); console.log(user.company.name); // Google console.log(user.cars.size); // 2 ``` -------------------------------- ### Access Relationships in EntityBase Source: https://github.com/brunomm/entity-base/blob/main/README.md Provides examples of accessing related data within an EntityBase model, including direct property access for 'belongsTo' relationships and using collection methods like 'get' for 'hasMany' relationships. ```javascript user.company.name user.cars.get(carId) user.array('cars').map(car => car.model) ``` -------------------------------- ### EntityBase Deep Tree Example Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Demonstrates creating and accessing a nested entity structure using EntityBase. It shows how to define relationships between entities like Inbox, Thread, and Message, and how to access nested data. ```javascript class MessageEntity extends EntityBase { static defaultAttributes = { text: '', read: false }; } class ThreadEntity extends EntityBase { static defaultAttributes = { title: '', messages: [] }; static hasMany = { messages: MessageEntity }; } class InboxEntity extends EntityBase { static defaultAttributes = { user_id: null, threads: [] }; static hasMany = { threads: ThreadEntity }; } const inbox = new InboxEntity({ user_id: 7, threads: [ { title: 'Support', messages: [{ text: 'Hello' }, { text: 'How can I help?' }] } ] }); const threads = inbox.threads; const firstThread = Array.from(threads.values())[0]; const messages = firstThread.messages; console.log(messages.size); // 2 ``` -------------------------------- ### Entity Validation Example Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Shows how to define validation rules for an entity and then validate its instance. The `.validate()` method returns an object with errors. ```javascript class AccountEntity extends EntityBase { static defaultAttributes = { email: '' }; static validates = { email: [(val) => ({ isValid: /^[^s@]+@[^s@]+\.[^s@]+$/.test(val), message: 'is invalid' })] }; } const account = new AccountEntity({ email: 'bad-email' }); const validated = account.validate(); console.log(validated.errors.fullMessages()); // ["Email is invalid"] ``` -------------------------------- ### Update Order Status and Nested Items Source: https://github.com/brunomm/entity-base/blob/main/docs/documentacao-abrangente.md Demonstrates updating the status of an order, modifying a specific nested item within the order, and adding a new item to the order. It also shows how the original objects remain unchanged due to immutability. ```javascript import { Customer, Address, Product, OrderItem, Payment, Order } from './marketplace_entities'; // ... (código para criar o pedido 'order' do Exemplo 3) // Para fins de exemplo, vamos recriar o pedido aqui: const customerAddress = new Address({ street: 'Av. Paulista', number: '1000', city: 'São Paulo', state: 'SP', zipCode: '01310-100' }); const customer = new Customer({ name: 'Ana Paula', email: 'ana.paula@example.com', address: customerAddress }); const productA = new Product({ name: 'Smartphone X', price: 3000, stock: 50 }); const productB = new Product({ name: 'Fone Bluetooth', price: 300, stock: 100 }); const item1 = new OrderItem({ product: productA, quantity: 1, unitPrice: productA.price }); const item2 = new OrderItem({ product: productB, quantity: 2, unitPrice: productB.price }); const payment = new Payment({ method: 'Credit Card', amount: (item1.quantity * item1.unitPrice) + (item2.quantity * item2.unitPrice), status: 'approved' }); let order = new Order({ customer: customer, items: [item1, item2], totalAmount: payment.amount, payment: payment, status: 'processing' }); console.log('Status inicial do pedido:', order.status); // processing // Atualizando o status do pedido const shippedOrder = order.set('status', 'shipped'); console.log('Status após envio:', shippedOrder.status); // shipped console.log('Pedido original inalterado:', order.status); // processing // Atualizando a quantidade de um item específico no pedido const item2Id = item2.idOrToken; // Obter o ID do item2 const [orderWithUpdatedItem, updatedItem2] = shippedOrder.updateNested('items', item2Id, { quantity: 3 }); console.log('Nova quantidade do Fone Bluetooth:', orderWithUpdatedItem.items.get(item2Id).quantity); // 3 console.log('Item original inalterado:', item2.quantity); // 2 // Atualizando o status de todos os itens do pedido para 'embalado' (exemplo hipotético) // Supondo que OrderItemivesse um atributo 'status' // const [orderWithItemsPacked, packedItems] = orderWithUpdatedItem.updateManyNested('items', { status: 'packed' }); // console.log(orderWithItemsPacked.items.values().next().value.status); // packed // Adicionando um novo item ao pedido const productC = new Product({ name: 'Smartwatch', price: 1200, stock: 30 }); const [orderWithNewItem, newItem3] = orderWithUpdatedItem.addNested('items', { product: productC, quantity: 1, unitPrice: productC.price }); console.log('Número total de itens após adicionar:', orderWithNewItem.items.size); // 3 console.log('Novo item adicionado:', newItem3.product.name); // Smartwatch ``` -------------------------------- ### Define Marketplace Entities with EntityBase Source: https://github.com/brunomm/entity-base/blob/main/docs/documentacao-abrangente.md Defines various entities for a marketplace, such as Address, Customer, Product, OrderItem, Payment, and Order, using the EntityBase library. Each entity includes default attributes, validation rules, and relationships (belongsTo, hasMany). The Order entity also includes a method to calculate the total value of its items. ```javascript // marketplace_entities.js import EntityBase from '@btec/entity-base' class Address extends EntityBase { static defaultAttributes = { street: '', number: '', complement: '', neighborhood: '', city: '', state: '', zipCode: '' }; static validates = { street: [(val) => ({ isValid: !!val, message: 'é obrigatório' })], city: [(val) => ({ isValid: !!val, message: 'é obrigatória' })], state: [(val) => ({ isValid: !!val, message: 'é obrigatório' })], zipCode: [(val) => ({ isValid: !!val, message: 'é obrigatório' })] }; } class Customer extends EntityBase { static defaultAttributes = { name: '', email: '', phone: '', address: null }; static belongsTo = { address: Address }; static validates = { name: [(val) => ({ isValid: !!val, message: 'é obrigatório' })], email: [ (val) => ({ isValid: !!val, message: 'é obrigatório' }), (val) => ({ isValid: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val), message: 'inválido' }) ] }; } class Product extends EntityBase { static defaultAttributes = { name: '', description: '', price: 0, stock: 0 }; static validates = { name: [(val) => ({ isValid: !!val, message: 'é obrigatório' })], price: [ (val) => ({ isValid: val > 0, message: 'deve ser maior que zero' }) ], stock: [ (val) => ({ isValid: val >= 0, message: 'não pode ser negativo' }) ] }; } class OrderItem extends EntityBase { static defaultAttributes = { product: null, quantity: 0, unitPrice: 0 }; static belongsTo = { product: Product }; static validates = { product: [(val) => ({ isValid: !!val, message: 'é obrigatório' })], quantity: [(val) => ({ isValid: val > 0, message: 'deve ser maior que zero' })] }; } class Payment extends EntityBase { static defaultAttributes = { method: '', amount: 0, status: 'pending' // pending, approved, rejected }; static validates = { method: [(val) => ({ isValid: !!val, message: 'é obrigatório' })], amount: [(val) => ({ isValid: val > 0, message: 'deve ser maior que zero' })], status: [(val) => ({ isValid: ['pending', 'approved', 'rejected'].includes(val), message: 'inválido' })] }; } class Order extends EntityBase { static defaultAttributes = { customer: null, items: [], totalAmount: 0, payment: null, status: 'pending' // pending, processing, shipped, delivered, cancelled }; static belongsTo = { customer: Customer, payment: Payment }; static hasMany = { items: OrderItem }; static validates = { customer: [(val) => ({ isValid: !!val, message: 'é obrigatório' })], items: [(val) => ({ isValid: val.size > 0, message: 'deve ter pelo menos um item' })], totalAmount: [(val) => ({ isValid: val > 0, message: 'deve ser maior que zero' })] }; totalValue() { return this.array('items').reduce((total, item) => total + (item.quantity * item.unitPrice), 0) } } export { Address, Customer, Product, OrderItem, Payment, Order }; ``` -------------------------------- ### Instantiate Entity Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Creates a new instance of an EntityBase subclass with provided attributes. ```javascript const user = new UserEntity({ name: 'Alice', age: 25 }); ``` -------------------------------- ### Create and Update EntityBase Instances Source: https://github.com/brunomm/entity-base/blob/main/README.md Shows how to create a new 'User' instance with initial attributes and how to update an existing instance immutably using the 'set' method. The 'set' method returns a new instance with the updated property. ```javascript const user = new User({ name: 'Alice', age: 25 }); const updatedUser = user.set('name', 'Bob'); console.log(user.name); // Alice console.log(updatedUser.name); // Bob ``` -------------------------------- ### Test EntityBase Immutability and Validation Source: https://github.com/brunomm/entity-base/blob/main/README.md Illustrates unit testing practices for EntityBase, focusing on verifying immutability when updating instances and checking the correctness of validation rules using assertion libraries like Jest or Vitest. ```javascript expect(user.set('name', 'Bob')).not.toBe(user); expect(user.validate().errors.isEmpty()).toBe(true); ``` -------------------------------- ### Serialization to Plain Object Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Demonstrates the use of the `.toObject()` method to convert an entity instance, including its relationships, into a plain JavaScript object. ```javascript const userObj = user.toObject(); ``` -------------------------------- ### Serialization for API Payload Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Explains the `.toParams()` method, which is used to prepare entity data for API submission. This method can be overridden for custom payload formatting. ```javascript const payload = user.toParams(); ``` -------------------------------- ### Serialize EntityBase to Plain JavaScript Object Source: https://github.com/brunomm/entity-base/blob/main/README.md Shows how to use the `toObject()` method to convert an EntityBase instance into a plain JavaScript object, useful for debugging or when a non-class representation is needed. ```javascript const raw = user.toObject(); ``` -------------------------------- ### Configure Default Attributes Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Defines the default values for each attribute in an EntityBase subclass. This is a required configuration option. ```javascript static defaultAttributes = { name: '', age: 0, active: true }; ``` -------------------------------- ### Serialize EntityBase to API Payload Source: https://github.com/brunomm/entity-base/blob/main/README.md Demonstrates the use of the `toParams()` method to serialize an EntityBase instance into a plain JavaScript object suitable for API submissions. This includes nested relationships. ```javascript const payload = user.toParams(); // { name: 'Alice', age: 25, company: { name: 'ACME' }, cars: [ { ... }, ... ] } ``` -------------------------------- ### Validate EntityBase Instance Data Source: https://github.com/brunomm/entity-base/blob/main/README.md Illustrates the validation process for an EntityBase instance. It creates an 'invalidUser' that violates validation rules and then uses the 'validate' method to check its validity and retrieve error messages. ```javascript const invalidUser = new User({ age: 16, company: { name: 'ACME' } }); const validated = invalidUser.validate(); console.log(validated.isValid()); // false console.log(validated.errors.fullMessages()); // → [ 'Company is allowed only for users over 18', 'Name is required' ] ``` -------------------------------- ### Define a User Model with EntityBase Source: https://github.com/brunomm/entity-base/blob/main/README.md Demonstrates how to define a 'User' model extending EntityBase. It includes default attributes, relationship definitions (belongsTo, hasMany), and declarative validations for properties like 'name' and 'company'. ```javascript import EntityBase from '@btec/entity-base' class User extends EntityBase { static defaultAttributes = { name: '', age: 0, company: null, cars: [] }; static belongsTo = { company: Company }; static hasMany = { cars: Car }; static validates = { name: [(val) => ({ isValid: !!val, message: 'is required' })], company: [ (val, entity) => ({ isValid: !val || entity.age >= 18, message: 'is allowed only for users over 18' }) ] }; } ``` -------------------------------- ### Access Entity Attributes Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Demonstrates accessing entity attributes using auto-generated getters or the `.get()` method. Relationships are also accessible directly. ```javascript user.name // → "Alice" user.get('name') // → "Alice" user.company // → CompanyEntity instance user.posts // → Map of PostEntity instances ``` -------------------------------- ### Configure Validation Rules Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Defines validation rules per field using validator functions. Each validator should return an object with `isValid` and an optional `message`. ```javascript static validates = { name: [(val) => ({ isValid: !!val, message: 'is required' })], age: [(val) => ({ isValid: val >= 18, message: 'must be at least 18' })] }; ``` -------------------------------- ### Configure 'hasMany' Relationships Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Defines plural child relationships for an EntityBase subclass. Values are stored as a Map where keys are IDs or tokens and values are Entity instances. ```javascript static hasMany = { posts: PostEntity, comments: CommentEntity }; ``` -------------------------------- ### Update Nested Entities Immutably Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Illustrates how to update a nested entity immutably by creating new Maps and entity instances for the changed parts. ```javascript const civicID = Array.from(user.cars.keys())[1]; const civic = user.cars.get(civicID); const updatedCivic = civic.set('price', 45000); const newCars = new Map(user.cars); newCars.set(civicID, updatedCivic); const updatedUser = user.set('cars', newCars); console.log(updatedUser.cars.get(civicID).price); // 45000 ``` -------------------------------- ### Update Entity Immutably Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Shows how to update an entity's attribute immutably. The `.set()` method returns a new entity instance with the updated value. ```javascript const updated = user.set('name', 'Bob'); console.log(user.name); // Alice console.log(updated.name); // Bob console.log(user !== updated); // true ``` -------------------------------- ### Configure 'belongsTo' Relationships Source: https://github.com/brunomm/entity-base/blob/main/docs/entity_base-documentation.md Defines singular parent relationships for an EntityBase subclass. Each value is stored as a single entity instance. ```javascript static belongsTo = { company: CompanyEntity }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.