DDD Entity classes and utilities
npm i @ts-ddd/entity
yarn add @ts-ddd/entity
pnpm install @ts-ddd/entity
bun add @ts-ddd/entity
import { Identifier, Entity } from '@ts-ddd/entity';
interface IBook {
id: Identifier;
name: string;
year: number;
publisher: string;
}
class Book extends Entity<IBook> {
public static create(payload: IBook) {
return new Book(payload);
}
public static createToPrimitives(payload: Omit<IBook, 'id'>) {
return new Book({
id: uuidGenerator(),
...payload
})
}
public static createFromPrimitives(payload: IBook): Book {
return new Book(payload)
}
}
const book = Book.createFromPrimitives({
id: '88d37945-cc6e-43b0-8872-9d378d4bb171',
name: "Harry Potter",
year: 1997,
publisher: "Bloomsbury"
});
const book = Book.createToPrimitives({
name: `Harry Potter and the Sorcerer's Stone`,
year: 1997,
publisher: "Bloomsbury"
});
book.getProperty('id') // 88d37945-cc6e-43b0-8872-9d378d4bb171
book.setProperty('name', `Harry Potter and the Sorcerer's Stone`)
book.toPrimitives()
/*
{
id: '88d37945-cc6e-43b0-8872-9d378d4bb171',
name: 'Harry Potter and the Sorcerer's Stone',
year: 1997,
publisher: 'Bloomsbury'
}
*/
---