Entities

An instance or class of type Entity that defines, and holds the data of a single resource record.

Entities represent the schema of your resources. They can hold validation rules, associations, type hinting and more. In this chapter, we'll be looking at what an entity looks like, how you can create one and what they're responsible for.

Creating

By default, aurelia-orm works with all resources, even if you don't supply a custom entity. When this happens, your entities won't have any decoration and aurelia-orm will allow all values to be set as-is.

But if you do want all these fizzy good make feel nice features, you'll want to keep on reading.

The class

Creating an entity is simple.

import {Entity} from 'aurelia-orm';

export class Product extends Entity {
}

That's it! That's all that's needed to create an entity.

Registering

After creating your gem of an Entity, you'll want to register it with the EntityManager. Then the Repository responsible for your resource will populate using your new entity!

Here's how:

import {EntityManager} from 'aurelia-orm';
import {inject} from 'aurelia-dependency-injection';
import {Product} from './entity/product';

@inject(EntityManager)
class SomeClass {
  constructor(entityManager) {
    entityManager.registerEntity(Product);
  }
}

There's an easier way to do this, as described in the chapter Configuration.

Going deep

Here's an example that showcases (almost) all possibilities for your entity:

import {ValidationRules} from 'aurelia-validation';
import {Entity, type, association, validatedResource} from 'aurelia-orm';

@validatedResource('product')
export class Product extends Entity {
  @type('string')
  name = null;

  @association('category')
  category = null;

  @association({collection: 'media'})
  media = [];

  constructor() {
    super();

    ValidationRules
      .ensure('name').required().minLength(8).maxLength(20)
      .on(this);  
  }
}

Further information on the decorators used are in the decorators chapter.

results matching ""

    No results matching ""