Skip to content

Documentation / @ember-data/json-api / index / default

Defined in: -private/cache.ts:146

A JSON:API Cache implementation.

What cache the store uses is configurable. Using a different implementation can be achieved by implementing the store's createCache hook.

This is the cache implementation used by ember-data.

js
import Cache from '@ember-data/json-api';
import Store from '@ember-data/store';

export default class extends Store {
  createCache(wrapper) {
    return new Cache(wrapper);
  }
}

Cache

Implements

Constructors

Constructor

ts
new default(capabilities): JSONAPICache;

Defined in: -private/cache.ts:167

Parameters

capabilities

CacheCapabilitiesManager

Returns

JSONAPICache

Properties

version

ts
version: "2";

Defined in: -private/cache.ts:154

The Cache Version that this implementation implements.

Implementation of

Cache.version

Methods

changedAttrs()

ts
changedAttrs(identifier): ChangedAttributesHash;

Defined in: -private/cache.ts:1416

Query the cache for the changed attributes of a resource.

Parameters

identifier

StableRecordIdentifier

Returns

ChangedAttributesHash

{ <field>: [<old>, <new>] }

Implementation of

Cache.changedAttrs


changedRelationships()

ts
changedRelationships(identifier): Map<string, RelationshipDiff>;

Defined in: -private/cache.ts:1529

Query the cache for the changes to relationships of a resource.

Returns a map of relationship names to RelationshipDiff objects.

ts
type RelationshipDiff =
| {
   kind: 'collection';
   remoteState: StableRecordIdentifier[];
   additions: Set<StableRecordIdentifier>;
   removals: Set<StableRecordIdentifier>;
   localState: StableRecordIdentifier[];
   reordered: boolean;
 }
| {
   kind: 'resource';
   remoteState: StableRecordIdentifier | null;
   localState: StableRecordIdentifier | null;
 };

Parameters

identifier

StableRecordIdentifier

Returns

Map<string, RelationshipDiff>

Implementation of

Cache.changedRelationships


clientDidCreate()

ts
clientDidCreate(identifier, options?): Record<string, unknown>;

Defined in: -private/cache.ts:768

[LIFECYCLE] Signal to the cache that a new record has been instantiated on the client

It returns properties from options that should be set on the record during the create process. This return value behavior is deprecated.

Parameters

identifier

StableRecordIdentifier

options?

Record<string, Value>

Returns

Record<string, unknown>

Implementation of

Cache.clientDidCreate


commitWasRejected()

ts
commitWasRejected(identifier, errors?): void;

Defined in: -private/cache.ts:1053

[LIFECYCLE] Signals to the cache that a resource was update via a save transaction failed.

Parameters

identifier

StableRecordIdentifier

errors?

ApiError[]

Returns

void

Implementation of

Cache.commitWasRejected


didCommit()

ts
didCommit(committedIdentifier, result): SingleResourceDataDocument;

Defined in: -private/cache.ts:909

[LIFECYCLE] Signals to the cache that a resource was successfully updated as part of a save transaction.

Parameters

committedIdentifier

StableRecordIdentifier

result

StructuredDataDocument<SingleResourceDocument>

Returns

SingleResourceDataDocument

Implementation of

Cache.didCommit


diff()

ts
diff(): Promise<Change[]>;

Defined in: -private/cache.ts:716

Generate the list of changes applied to all record in the store.

Each individual resource or document that has been mutated should be described as an individual Change entry in the returned array.

A Change is described by an object containing up to three properties: (1) the identifier of the entity that changed; (2) the op code of that change being one of upsert or remove, and if the op is upsert a patch containing the data to merge into the cache for the given entity.

This patch is opaque to the Store but should be understood by the Cache and may expect to be utilized by an Adapter when generating data during a save operation.

It is generally recommended that the patch contain only the updated state, ignoring fields that are unchanged

ts
interface Change {
 identifier: StableRecordIdentifier | StableDocumentIdentifier;
 op: 'upsert' | 'remove';
 patch?: unknown;
}

Returns

Promise<Change[]>

Implementation of

Cache.diff


dump()

ts
dump(): Promise<ReadableStream<unknown>>;

Defined in: -private/cache.ts:731

Serialize the entire contents of the Cache into a Stream which may be fed back into a new instance of the same Cache via cache.hydrate.

Returns

Promise<ReadableStream<unknown>>

Implementation of

Cache.dump


getAttr()

ts
getAttr(identifier, attr): 
  | undefined
  | Value;

Defined in: -private/cache.ts:1165

Retrieve the data for an attribute from the cache

Parameters

identifier

StableRecordIdentifier

attr

string | string[]

Returns

| undefined | Value

Implementation of

Cache.getAttr


getErrors()

ts
getErrors(identifier): ApiError[];

Defined in: -private/cache.ts:1610

Query the cache for any validation errors applicable to the given resource.

Parameters

identifier

StableRecordIdentifier

Returns

ApiError[]

Implementation of

Cache.getErrors


getRelationship()

ts
getRelationship(identifier, field): 
  | ResourceRelationship<StableRecordIdentifier>
| CollectionRelationship<StableRecordIdentifier>;

Defined in: -private/cache.ts:1572

Query the cache for the current state of a relationship property

Parameters

identifier

StableRecordIdentifier

field

string

Returns

| ResourceRelationship<StableRecordIdentifier> | CollectionRelationship<StableRecordIdentifier>

resource relationship object

Implementation of

Cache.getRelationship


getRemoteAttr()

ts
getRemoteAttr(identifier, attr): 
  | undefined
  | Value;

Defined in: -private/cache.ts:1230

Retrieve remote state without any local changes for a specific attribute

Parameters

identifier

StableRecordIdentifier

attr

string | string[]

Returns

| undefined | Value

Implementation of

Cache.getRemoteAttr


getRemoteRelationship()

ts
getRemoteRelationship(identifier, field): 
  | ResourceRelationship<StableRecordIdentifier>
| CollectionRelationship<StableRecordIdentifier>;

Defined in: -private/cache.ts:1576

Query the cache for the server state of a relationship property without any local changes

Parameters

identifier

StableRecordIdentifier

field

string

Returns

| ResourceRelationship<StableRecordIdentifier> | CollectionRelationship<StableRecordIdentifier>

resource relationship object

Implementation of

Cache.getRemoteRelationship


hasChangedAttrs()

ts
hasChangedAttrs(identifier): boolean;

Defined in: -private/cache.ts:1440

Query the cache for whether any mutated attributes exist

Parameters

identifier

StableRecordIdentifier

Returns

boolean

Implementation of

Cache.hasChangedAttrs


hasChangedRelationships()

ts
hasChangedRelationships(identifier): boolean;

Defined in: -private/cache.ts:1540

Query the cache for whether any mutated relationships exist

Parameters

identifier

StableRecordIdentifier

Returns

boolean

Implementation of

Cache.hasChangedRelationships


hydrate()

ts
hydrate(stream): Promise<void>;

Defined in: -private/cache.ts:751

hydrate a Cache from a Stream with content previously serialized from another instance of the same Cache, resolving when hydration is complete.

This method should expect to be called both in the context of restoring the Cache during application rehydration after SSR AND at unknown times during the lifetime of an already booted application when it is desired to bulk-load additional information into the cache. This latter behavior supports optimizing pre/fetching of data for route transitions via data-only SSR modes.

Parameters

stream

ReadableStream<unknown>

Returns

Promise<void>

Implementation of

Cache.hydrate


isDeleted()

ts
isDeleted(identifier): boolean;

Defined in: -private/cache.ts:1647

Query the cache for whether a given resource is marked as deleted (but not necessarily persisted yet).

Parameters

identifier

StableRecordIdentifier

Returns

boolean

Implementation of

Cache.isDeleted


isDeletionCommitted()

ts
isDeletionCommitted(identifier): boolean;

Defined in: -private/cache.ts:1660

Query the cache for whether a given resource has been deleted and that deletion has also been persisted.

Parameters

identifier

StableRecordIdentifier

Returns

boolean

Implementation of

Cache.isDeletionCommitted


isEmpty()

ts
isEmpty(identifier): boolean;

Defined in: -private/cache.ts:1621

Query the cache for whether a given resource has any available data

Parameters

identifier

StableRecordIdentifier

Returns

boolean

Implementation of

Cache.isEmpty


isNew()

ts
isNew(identifier): boolean;

Defined in: -private/cache.ts:1634

Query the cache for whether a given resource was created locally and not yet persisted.

Parameters

identifier

StableRecordIdentifier

Returns

boolean

Implementation of

Cache.isNew


merge()

ts
merge(cache): Promise<void>;

Defined in: -private/cache.ts:680

Merge a fork back into a parent Cache.

Applications should typically not call this method themselves, preferring instead to merge at the Store level, which will utilize this method to merge the caches.

Parameters

cache

Cache

Returns

Promise<void>

Implementation of

Cache.merge


mutate()

ts
mutate(mutation): void;

Defined in: -private/cache.ts:440

Update the "local" or "current" (unpersisted) state of the Cache

Parameters

mutation

LocalRelationshipOperation

Returns

void

Implementation of

Cache.mutate


patch()

ts
patch(op): void;

Defined in: -private/cache.ts:411

Update the "remote" or "canonical" (persisted) state of the Cache by merging new information into the existing state.

Parameters

op

the operation or list of operations to perform

Operation | Operation[]

Returns

void

Implementation of

Cache.patch


peek()

Call Signature

ts
peek(identifier): 
  | null
  | ResourceObject;

Defined in: -private/cache.ts:491

Peek resource data from the Cache.

In development, if the return value is JSON the return value will be deep-cloned and deep-frozen to prevent mutation thereby enforcing cache Immutability.

This form of peek is useful for implementations that want to feed raw-data from cache to the UI or which want to interact with a blob of data directly from the presentation cache.

An implementation might want to do this because de-referencing records which read from their own blob is generally safer because the record does not require retainining connections to the Store and Cache to present data on a per-field basis.

This generally takes the place of getAttr as an API and may even take the place of getRelationship depending on implementation specifics, though this latter usage is less recommended due to the advantages of the Graph handling necessary entanglements and notifications for relational data.

Parameters
identifier

StableRecordIdentifier

Returns

| null | ResourceObject

the known resource data

Implementation of

Cache.peek

Call Signature

ts
peek(identifier): 
  | null
  | ResourceDocument;

Defined in: -private/cache.ts:492

Peek resource data from the Cache.

In development, if the return value is JSON the return value will be deep-cloned and deep-frozen to prevent mutation thereby enforcing cache Immutability.

This form of peek is useful for implementations that want to feed raw-data from cache to the UI or which want to interact with a blob of data directly from the presentation cache.

An implementation might want to do this because de-referencing records which read from their own blob is generally safer because the record does not require retainining connections to the Store and Cache to present data on a per-field basis.

This generally takes the place of getAttr as an API and may even take the place of getRelationship depending on implementation specifics, though this latter usage is less recommended due to the advantages of the Graph handling necessary entanglements and notifications for relational data.

Parameters
identifier

StableDocumentIdentifier

Returns

| null | ResourceDocument

the known resource data

Implementation of

Cache.peek


peekRemoteState()

Call Signature

ts
peekRemoteState(identifier): 
  | null
  | ResourceObject;

Defined in: -private/cache.ts:551

Peek remote resource data from the Cache.

This will give the data provided from the server without any local changes.

In development, if the return value is JSON the return value will be deep-cloned and deep-frozen to prevent mutation thereby enforcing cache Immutability.

This form of peek is useful for implementations that want to feed raw-data from cache to the UI or which want to interact with a blob of data directly from the presentation cache.

An implementation might want to do this because de-referencing records which read from their own blob is generally safer because the record does not require retainining connections to the Store and Cache to present data on a per-field basis.

This generally takes the place of getAttr as an API and may even take the place of getRelationship depending on implementation specifics, though this latter usage is less recommended due to the advantages of the Graph handling necessary entanglements and notifications for relational data.

Parameters
identifier

StableRecordIdentifier

Returns

| null | ResourceObject

the known resource data

Implementation of

Cache.peekRemoteState

Call Signature

ts
peekRemoteState(identifier): 
  | null
  | ResourceDocument;

Defined in: -private/cache.ts:552

Parameters
identifier

StableDocumentIdentifier

Returns

| null | ResourceDocument

Implementation of

Cache.peekRemoteState


peekRequest()

ts
peekRequest(identifier): 
  | null
| StructuredDocument<ResourceDocument>;

Defined in: -private/cache.ts:621

Peek the Cache for the existing request data associated with a cacheable request.

This is effectively the reverse of put for a request in that it will return the the request, response, and content whereas peek will return just the content.

Parameters

identifier

StableDocumentIdentifier

Returns

| null | StructuredDocument<ResourceDocument>

Implementation of

Cache.peekRequest


put()

Call Signature

ts
put<T>(doc): SingleResourceDataDocument;

Defined in: -private/cache.ts:217

Cache the response to a request

Implements Cache.put.

Expects a StructuredDocument whose content member is a JsonApiDocument.

js
cache.put({
  request: { url: 'https://api.example.com/v1/user/1' },
  content: {
    data: {
      type: 'user',
      id: '1',
      attributes: {
        name: 'Chris'
      }
    }
  }
})

Note The nested content and data members are not a mistake. This is because there are two separate concepts involved here, the StructuredDocument which contains the context of a given Request that has been issued with the returned contents as its content property, and a JSON:API Document which is the json contents returned by this endpoint and which uses its data property to signify which resources are the primary resources associated with the request.

StructuredDocument's with urls will be cached as full documents with associated resource membership order and contents preserved but linked into the cache.

Type Parameters
T

T extends SingleResourceDocument

Parameters
doc

StructuredDataDocument<T>

Returns

SingleResourceDataDocument

Implementation of

Cache.put

Call Signature

ts
put<T>(doc): CollectionResourceDataDocument;

Defined in: -private/cache.ts:218

Cache the response to a request

Implements Cache.put.

Expects a StructuredDocument whose content member is a JsonApiDocument.

js
cache.put({
  request: { url: 'https://api.example.com/v1/user/1' },
  content: {
    data: {
      type: 'user',
      id: '1',
      attributes: {
        name: 'Chris'
      }
    }
  }
})

Note The nested content and data members are not a mistake. This is because there are two separate concepts involved here, the StructuredDocument which contains the context of a given Request that has been issued with the returned contents as its content property, and a JSON:API Document which is the json contents returned by this endpoint and which uses its data property to signify which resources are the primary resources associated with the request.

StructuredDocument's with urls will be cached as full documents with associated resource membership order and contents preserved but linked into the cache.

Type Parameters
T

T extends CollectionResourceDocument

Parameters
doc

StructuredDataDocument<T>

Returns

CollectionResourceDataDocument

Implementation of
ts
Cache.put

Call Signature

ts
put<T>(doc): ResourceErrorDocument;

Defined in: -private/cache.ts:219

Cache the response to a request

Implements Cache.put.

Expects a StructuredDocument whose content member is a JsonApiDocument.

js
cache.put({
  request: { url: 'https://api.example.com/v1/user/1' },
  content: {
    data: {
      type: 'user',
      id: '1',
      attributes: {
        name: 'Chris'
      }
    }
  }
})

Note The nested content and data members are not a mistake. This is because there are two separate concepts involved here, the StructuredDocument which contains the context of a given Request that has been issued with the returned contents as its content property, and a JSON:API Document which is the json contents returned by this endpoint and which uses its data property to signify which resources are the primary resources associated with the request.

StructuredDocument's with urls will be cached as full documents with associated resource membership order and contents preserved but linked into the cache.

Type Parameters
T

T extends ResourceErrorDocument

Parameters
doc

StructuredErrorDocument<T>

Returns

ResourceErrorDocument

Implementation of
ts
Cache.put

Call Signature

ts
put<T>(doc): ResourceMetaDocument;

Defined in: -private/cache.ts:220

Cache the response to a request

Implements Cache.put.

Expects a StructuredDocument whose content member is a JsonApiDocument.

js
cache.put({
  request: { url: 'https://api.example.com/v1/user/1' },
  content: {
    data: {
      type: 'user',
      id: '1',
      attributes: {
        name: 'Chris'
      }
    }
  }
})

Note The nested content and data members are not a mistake. This is because there are two separate concepts involved here, the StructuredDocument which contains the context of a given Request that has been issued with the returned contents as its content property, and a JSON:API Document which is the json contents returned by this endpoint and which uses its data property to signify which resources are the primary resources associated with the request.

StructuredDocument's with urls will be cached as full documents with associated resource membership order and contents preserved but linked into the cache.

Type Parameters
T

T extends ResourceMetaDocument

Parameters
doc

StructuredDataDocument<T>

Returns

ResourceMetaDocument

Implementation of
ts
Cache.put

rollbackAttrs()

ts
rollbackAttrs(identifier): string[];

Defined in: -private/cache.ts:1468

Tell the cache to discard any uncommitted mutations to attributes

This method is a candidate to become a mutation

Parameters

identifier

StableRecordIdentifier

Returns

string[]

the names of fields that were restored

Implementation of

Cache.rollbackAttrs


rollbackRelationships()

ts
rollbackRelationships(identifier): string[];

Defined in: -private/cache.ts:1555

Tell the cache to discard any uncommitted mutations to relationships.

This will also discard the change on any appropriate inverses.

This method is a candidate to become a mutation

Parameters

identifier

StableRecordIdentifier

Returns

string[]

the names of relationships that were restored

Implementation of

Cache.rollbackRelationships


setAttr()

ts
setAttr(
   identifier, 
   attr, 
   value): void;

Defined in: -private/cache.ts:1299

Mutate the data for an attribute in the cache

This method is a candidate to become a mutation

Parameters

identifier

StableRecordIdentifier

attr

string | string[]

value

Value

Returns

void

Implementation of

Cache.setAttr


setIsDeleted()

ts
setIsDeleted(identifier, isDeleted): void;

Defined in: -private/cache.ts:1596

Update the cache state for the given resource to be marked as locally deleted, or remove such a mark.

This method is a candidate to become a mutation

Parameters

identifier

StableRecordIdentifier

isDeleted

boolean

Returns

void

Implementation of

Cache.setIsDeleted


unloadRecord()

ts
unloadRecord(identifier): void;

Defined in: -private/cache.ts:1083

[LIFECYCLE] Signals to the cache that all data for a resource should be cleared.

This method is a candidate to become a mutation

Parameters

identifier

StableRecordIdentifier

Returns

void

Implementation of

Cache.unloadRecord


upsert()

ts
upsert(
   identifier, 
   data, 
   calculateChanges?): void | string[];

Defined in: -private/cache.ts:634

Push resource data from a remote source into the cache for this identifier

Parameters

identifier

StableRecordIdentifier

data

ExistingResourceObject

calculateChanges?

boolean

Returns

void | string[]

if hasRecord is true then calculated key changes should be returned

Implementation of

Cache.upsert


willCommit()

ts
willCommit(identifier): void;

Defined in: -private/cache.ts:847

[LIFECYCLE] Signals to the cache that a resource will be part of a save transaction.

Parameters

identifier

StableRecordIdentifier

Returns

void

Implementation of

Cache.willCommit

Released under the MIT License.