Skip to main content

EntityMixin

Entity defines a single unique object.

If you already have classes for your data-types, EntityMixin may be for you.

import { EntityMixin } from '@data-client/rest';

export class Article {
  id = '';
  title = '';
  content = '';
  tags: string[] = [];
}

export class ArticleEntity extends EntityMixin(Article) {}

Options

The second argument to the mixin can be used to conveniently customize construction. If not specified the Base class' static members will be used. Alternatively, just like with Entity, you can always specify these as static members of the final class.

class User {
  username = '';
  createdAt = Temporal.Instant.fromEpochSeconds(0);
}
class UserEntity extends EntityMixin(User, {
  pk: 'username',
  key: 'User',
  schema: { createdAt: Temporal.Instant.from },
}) {}

pk: string | (value, parent?, key?, args?) => string | number | undefined = 'id'

Specifies the Entity.pk

A string indicates the field to use for pk.

A function is used just like Entity.pk, but the first argument (value) is this

Defaults to 'id'; which means pk is a required option unless the Base class has a serializable id member.

multi-column primary key
class Thread {
  forum = '';
  slug = '';
  content = '';
}
class ThreadEntity extends EntityMixin(Thread, {
  pk(value) {
    return [value.forum, value.slug].join(',');
  },
}) {}

key: string

Specifies the Entity.key

schema: {[k:string]: Schema}

Specifies the Entity.schema

Methods

EntityMixin has the same methods as the Entity class.

const vs class

If you don't need to further customize the entity, you can use a const declaration instead of extend to another class.

There is a subtle difference when referring to the class token in TypeScript - as class declarations will refer to the instance type; whereas const tokens refer to the value, so you must use typeof, but additionally typeof gives the class type, so you must layer InstanceType on top.

import { schema } from '@data-client/rest';

export class Article {
  id = '';
  title = '';
  content = '';
  tags: string[] = [];
}

export class ArticleEntity extends EntityMixin(Article) {}
export const ArticleEntity2 = EntityMixin(Article);

const article: ArticleEntity = ArticleEntity.fromJS();
const articleFails: ArticleEntity2 = ArticleEntity2.fromJS();
const articleWorks: InstanceType<typeof ArticleEntity2> =
  ArticleEntity2.fromJS();