import TypeScriptEditor from '@site/src/components/TypeScriptEditor';
import CodeBlock from '@theme/CodeBlock';
### static fromJS(props): Entity {#fromJS}
Factory method that copies props to a new instance. Use this instead of `new MyEntity()`,
to ensure default props are overridden. It does not call [process()](#process).
### static process(input, parent, key, args): processedEntity {#process}
Run at the start of normalization for this entity. Return value is saved in store
and sent to [pk()](#pk).
**Defaults** to simply copying the response (`{...input}`)
`parent` is the object that nests this entity, and `key` is the field it is under. An entity in a nested list gets
the parent and key of the list. At the top level of a response, `key` is `undefined`. When two kinds of parent
nest this entity under the same `key`, also check a field that only one of them has.
How to override to [build reverse-lookups for relational data](../guides/relational-data.md#reverse-lookups)
#### Case of the missing id
{props?.entitySyntax === 'EntityMixin' ? (
{`import { EntityMixin } from '@data-client/rest';
class Stream {
username = '';
title = '';
game = '';
currentViewers = 0;
live = false;
}
class StreamEntity extends EntityMixin(Stream) {
static key = 'Stream';
static process(value, parent, key, args) {
// super.process creates a copy of value
const processed = super.process(value, parent, key, args);
processed.username = args[0]?.username;
return processed;
}
}`}
) : (
{`class Stream extends Entity {
username = '';
title = '';
game = '';
currentViewers = 0;
live = false;
pk() {
return this.username;
}
static key = 'Stream';
static process(value, parent, key, args) {
// super.process creates a copy of value
const processed = super.process(value, parent, key, args);
processed.username = args[0]?.username;
return processed;
}
}`}
)}
#### Dynamic Invalidation
Returning `undefined` from [Entity.process](#process)
will cause the `Entity` to be [invalidated](/docs/concepts/expiry-policy#invalidate-entity).
This this allows us to invalidate dynamically; based on the particular response data.
{props?.entitySyntax === 'EntityMixin' ? (
{`import { EntityMixin } from '@data-client/rest';
class PriceLevel {
price = 0;
amount = 0;
}
class PriceLevelEntity extends EntityMixin(PriceLevel) {
static process(
input: [number, number],
parent: any,
key: string | undefined,
): any {
const [price, amount] = input;
// highlight-next-line
if (amount === 0) return undefined;
return { price, amount };
}
}`}
) : (
{`class PriceLevel extends Entity {
price = 0;
amount = 0;
pk() {
return this.price;
}
static process(
input: [number, number],
parent: any,
key: string | undefined,
): any {
const [price, amount] = input;
// highlight-next-line
if (amount === 0) return undefined;
return { price, amount };
}
}`}
)}
### static mergeWithStore(existingMeta, incomingMeta, existing, incoming): mergedValue {#mergeWithStore}
```typescript
static mergeWithStore(
existingMeta: {
date: number;
fetchedAt: number;
},
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
const shouldUpdate = this.shouldUpdate(
existingMeta,
incomingMeta,
existing,
incoming,
);
if (shouldUpdate) {
// distinct types are not mergeable (like delete symbol), so just replace
if (typeof incoming !== typeof existing) {
return incoming;
} else {
return this.shouldReorder(
existingMeta,
incomingMeta,
existing,
incoming,
)
? this.merge(incoming, existing)
: this.merge(existing, incoming);
}
} else {
return existing;
}
}
```
`mergeWithStore()` is called during normalization when a processed entity is already found in the store.
This calls [shouldUpdate()](#shouldupdate), [shouldReorder()](#shouldreorder) and potentially [merge()](#merge)
### static shouldUpdate(existingMeta, incomingMeta, existing, incoming): boolean {#shouldupdate}
```typescript
static shouldUpdate(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
return existingMeta.fetchedAt <= incomingMeta.fetchedAt;
}
```
#### Preventing updates
shouldUpdate can also be used to short-circuit an entity update.
{props?.entitySyntax === 'EntityMixin' ? (
{`import deepEqual from 'deep-equal';
import { EntityMixin } from '@data-client/rest';
class Article {
id = '';
title = '';
content = '';
published = false;
}
class ArticleEntity extends EntityMixin(Article) {
static shouldUpdate(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
return !deepEqual(incoming, existing);
}
}`}
) : (
{`import deepEqual from 'deep-equal';
class Article extends Entity {
id = '';
title = '';
content = '';
published = false;
static shouldUpdate(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
return !deepEqual(incoming, existing);
}
}`}
)}
### static shouldReorder(existingMeta, incomingMeta, existing, incoming): boolean {#shouldreorder}
```typescript
static shouldReorder(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
return incomingMeta.fetchedAt < existingMeta.fetchedAt;
}
```
`true` return value will reorder incoming vs in-store entity argument order in merge. With
the default merge, this will cause the fields of existing entities to override those of incoming,
rather than the other way around.
#### Example
{props?.entitySyntax === 'EntityMixin' ? (
{`import { EntityMixin } from '@data-client/rest';
class LatestPrice {
id = '';
updatedAt = 0;
price = '0.0';
symbol = '';
}
class LatestPriceEntity extends EntityMixin(LatestPrice) {
static shouldReorder(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: { updatedAt: number },
incoming: { updatedAt: number },
) {
return incoming.updatedAt < existing.updatedAt;
}
}`}
) : (
{`class LatestPriceEntity extends Entity {
id = '';
updatedAt = 0;
price = '0.0';
symbol = '';
pk() {
return this.id;
}
static shouldReorder(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: { updatedAt: number },
incoming: { updatedAt: number },
) {
return incoming.updatedAt < existing.updatedAt;
}
}`}
)}
import StackBlitz from '@site/src/components/StackBlitz';
### static merge(existing, incoming): mergedValue {#merge}
```typescript
static merge(existing: any, incoming: any) {
return {
...existing,
...incoming,
};
}
```
Merge is used to handle cases when an incoming entity is already found. This is called directly
when the same entity is found in one response. By default it is also called when [mergeWithStore()](#mergeWithStore)
determines the incoming entity should be merged with an entity already persisted in the Reactive Data Client store.
How to override to [build reverse-lookups for relational data](../guides/relational-data.md#reverse-lookups)
### static mergeMetaWithStore(existingMeta, incomingMeta, existing, incoming): meta {#mergeMetaWithStore}
```typescript
static mergeMetaWithStore(
existingMeta: {
expiresAt: number;
date: number;
fetchedAt: number;
},
incomingMeta: { expiresAt: number; date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
return this.shouldReorder(existingMeta, incomingMeta, existing, incoming)
? existingMeta
: incomingMeta;
}
```
`mergeMetaWithStore()` is called during normalization when a processed entity is already found in the store.
### static queryKey(args, unvisit, delegate): pk? {#queryKey}
This method enables `Entities` to be [Queryable](/rest/api/schema#queryable) - allowing store access without an endpoint.
Overriding can allow customization or disabling of this behavior altogether.
Returning `undefined` will disallow this behavior.
Returning `pk` string will attempt to lookup this entity and use in the response.
When used, expiry policy is computed based on the entity's own meta data.
By **default** uses the first argument to lookup in [pk()](#pk) and [indexes](/rest/api/Entity#indexes)
`delegate` reads the store. Its members are listed in [IQueryDelegate](/rest/api/SchemaSimple#iquerydelegate).
```ts title="Look up by pk"
if (delegate.getEntity(this.key, id)) return id;
```
```ts title="Look up by index"
const pk = delegate.getIndex(this.key, indexName, args[0][indexName]);
if (pk && delegate.getEntity(this.key, pk)) return pk;
```
### static createIfValid(processedEntity): Entity | undefined {#createIfValid}
Called when denormalizing an entity. This will create an instance of this class
if it is deemed 'valid'.
`undefined` return will result in [Invalid expiry status](/docs/concepts/expiry-policy#expiry-status),
like [Invalidate](/rest/api/Invalidate).
[`Invalid`](/docs/concepts/expiry-policy#expiry-status) expiry generally means :react[hooks]:vue[composables] will enter a loading state and attempt a new fetch.
```ts
static createIfValid(props): AbstractInstanceType | undefined {
if (this.validate(props)) {
return undefined as any;
}
return this.fromJS(props);
}
```
### static validate(processedEntity): errorMessage? {#validate}
Runs during both normalize and denormalize. Returning a string indicates an error (the string is the message).
During normalization a validation failure will result in an error for that fetch.
During denormalization a validation failure will mark that result as 'invalid' and thus
will block on fetching a result.
By **default** does some basic field existence checks in development mode only. Override to
disable or customize.
[Using validation for endpoints with incomplete fields](../guides/partial-entities.md)