Creating Entities

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:

$bit
Copiedcopy
See command synopsis

The command above will generate a new component with a Person data transfer objects for you to use.

Write the code

Classes use an easy way to describe entities as you can enhance them with new traits via properties and methods as you learn new needs. 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(plainBeer: PlainBeer) {
    return new Beer(
      plainBeer.name,
      plainBeer.author
    );
  }
}
CopiedCopy

The toObject() and static from() methods are used for serialization and deserialization methods 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 the API

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';
CopiedCopy

Mocking entities

It is a good practice to provide API for mock data of the entity and provide it 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,
  ]
];
CopiedCopy

Testing entities

You can test the behaviour in the book.spec.ts file, and using the mock objects above, this makes testing easy for you but 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');
});
CopiedCopy