Base Entities
Every model needs an identifier, most need to know when they were created or last changed, and some need deletes to be reversible or updates to be versioned. Extend one of the base classes below instead of writing those fields by hand on every entity. This page also covers @TrackChanges, for keeping a history of changes to a record, and @ChildEntity, for letting related model classes share a single collection or table instead of each getting their own.
Base entity classes
| Class | Adds |
|---|---|
SimpleEntity | just uid (a UUID primary key) |
BaseEntity | uid, dateCreated, dateModified, version (for optimistic locking) |
SimpleMongoEntity | SimpleEntity + a MongoDB _id column |
BaseMongoEntity | BaseEntity + a MongoDB _id column |
RecoverableBaseEntity | BaseEntity + a deleted soft-delete flag |
RecoverableBaseMongoEntity | RecoverableBaseEntity + a MongoDB _id column |
import { BaseMongoEntity, PersistenceDecorators, ModelDecorators } from '@rapidrest/service-core';
const { Entity, Column } = PersistenceDecorators;
const { DataStore } = ModelDecorators;
@Entity()
@DataStore('mongo')
export class Pet extends BaseMongoEntity {
@Column()
name: string = '';
@Column()
species: string = '';
constructor(other?: Partial<Pet>) {
super(other);
Object.assign(this, other);
}
}
Reach for RecoverableBaseEntity when a delete should be reversible, records get flagged deleted: true rather than actually removed. BaseEntity's version field gives every entity optimistic-locking updates for free, already wired into Auto CRUD Routes without any extra code.
@TrackChanges(versions?)
Keeps historical versions of a record every time it's updated:
@TrackChanges() // keeps every version (default: -1)
@DataStore('mongo')
export class VersionedUser extends RecoverableBaseMongoEntity {}
@TrackChanges(5) // keeps only the last 5 versions
export class AuditedRecord extends BaseMongoEntity {}
@ChildEntity()
Lets multiple entity classes share a single collection/table, discriminated by type, an inheritance hierarchy without a separate collection per subclass:
@Entity()
@DataStore('mongo')
export class User extends BaseMongoEntity {
@Column() name: string = '';
}
@ChildEntity()
export class Player extends User {
@Reference(Item)
items?: string[];
}
@Reference(EntityClass) marks a property as referencing another entity by identifier, rather than embedding it directly.