An entity component is used to provide a clear and consistent API for accessing data transfer objects. You can create an entity by running the following command:
The command above will generate a new component with a Book data transfer object for you to use.
Classes are an easy way to describe entities, as you can enhance them with new traits via properties and methods as new needs arise. Below is an example Book entity implemented in the book.ts file of the component:
export type PlainBook = {
name: string;
author: string;
}
export class Book {
constructor(
/**
* name of the book.
*/
readonly name: string,
/**
* author of the book.
*/
readonly author: string,
) {}
/**
* serialize a Book object into a plain object.
*/
toObject() {
return {
name: this.name,
author: this.author,
};
}
/**
* create a Book object from a plain object.
*/
static from(plainBook: PlainBook) {
return new Book(
plainBook.name,
plainBook.author
);
}
}The toObject() and static from() methods provide serialization and deserialization as needed for your data entities.
It is worthwhile to add JSDoc comments on your code. Use bit start to preview your component API reference and head to the component's API reference tab.
Expose your entity in the component index.ts to allow access for your objects:
export { Book } from './book.js';
export type { PlainBook } from './book.js';It is a good practice to provide an API for mock data of the entity as part of the component API. Add a book.mock.ts file for your mock objects:
import type { PlainBook } from './book.js';
export const lordOfRings: PlainBook = {
name: 'Lord of the rings',
author: 'JRR Tolkien'
};
export const topBooks: PlainBook[] = [
{
name: 'Relativity: the special and the general theory',
author: 'Albert Einstein'
},
lordOfRings,
];You can test the behavior in the book.spec.ts file. Using the mock objects above makes testing easy for you, and also for people using your component:
import { Book } from './book.js';
import { lordOfRings } from './book.mock.js';
it('should be lord of the rings', () => {
const lordOfRingsBook = Book.from(lordOfRings);
expect(lordOfRingsBook.name).toEqual('Lord of the rings');
});