@types/ember-data
- Version 4.4.16
- Published
- 90.5 kB
- 4 dependencies
- MIT license
Install
npm i @types/ember-data
yarn add @types/ember-data
pnpm add @types/ember-data
Overview
TypeScript definitions for ember-data
Index
Interfaces
Namespaces
DS
- AbortError
- Adapter
- Adapter
- AdapterError
- AdapterPopulatedRecordArray
- Async
- AsyncBelongsTo
- AsyncHasMany
- attr()
- AttrOptions
- belongsTo()
- BelongsToReference
- BooleanTransform
- BuildURLMixin
- ConflictError
- DateTransform
- EmbeddedRecordsMixin
- Errors
- Errors
- errorsArrayToHash()
- errorsHashToArray()
- FilteredRecordArray
- ForbiddenError
- hasMany()
- HasManyReference
- InvalidError
- JSONAPIAdapter
- JSONAPISerializer
- JSONSerializer
- ManyArray
- ManyArray
- Model
- normalizeModelName()
- NotFoundError
- NumberTransform
- PromiseArray
- PromiseArray
- PromiseManyArray
- PromiseObject
- PromiseObject
- RecordArray
- RecordArray
- RecordReference
- RelationshipOptions
- RESTAdapter
- RESTAdapter
- RESTSerializer
- RootState
- Serializer
- ServerError
- Snapshot
- SnapshotRecordArray
- Store
- StringTransform
- Sync
- SyncHasMany
- TimeoutError
- Transform
- TransformType
- UnauthorizedError
- VERSION
Interfaces
interface AttributeSchema
interface AttributeSchema {}
interface ChangedAttributes
interface ChangedAttributes {}
index signature
[key: string]: [any, any] | undefined;
interface ModelSchema
interface ModelSchema<ModelName extends keyof ModelRegistry = keyof ModelRegistry> {}
property attributes
attributes: Map<string, AttributeSchema>;
property fields
fields: Map<string, 'attribute' | 'belongsTo' | 'hasMany'>;
property modelName
modelName: ModelName;
property relationshipsByName
relationshipsByName: Map<string, RelationshipSchema>;
method eachAttribute
eachAttribute: <T>( callback: (this: T, key: string, attribute: AttributeSchema) => void, binding?: T) => void;
method eachRelationship
eachRelationship: <T>( callback: (this: T, key: string, relationship: RelationshipSchema) => void, binding?: T) => void;
method eachTransformedAttribute
eachTransformedAttribute: <T>( callback: (this: T, key: string, relationship: RelationshipSchema) => void, binding?: T) => void;
interface RelationshipSchema
interface RelationshipSchema {}
Namespaces
namespace DS
namespace DS {}
variable VERSION
const VERSION: string;
function attr
attr: { <K extends string | number | symbol>( type: K, options?: AttrOptions<TransformType<K>> ): Ember.ComputedProperty<any>; (options?: AttrOptions<any>): Ember.ComputedProperty<any>; (target: any, propertyKey: string): void;};
DS.attr
defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types:string
,number
,boolean
anddate
. You can define your own transforms by subclassing [DS.Transform](/api/data/classes/DS.Transform.html).
function belongsTo
belongsTo: { <K extends string | number | symbol>( modelName: K, options: RelationshipOptions<ModelRegistry[K]> & Sync ): Ember.ComputedProperty<any, any>; <K extends string | number | symbol>( modelName: K, options?: RelationshipOptions<ModelRegistry> & Async ): Ember.ComputedProperty<AsyncBelongsTo<any>, any>;};
DS.belongsTo
is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html).
function errorsArrayToHash
errorsArrayToHash: (errors: any[]) => {};
Convert an array of errors in JSON-API format into an object.
function errorsHashToArray
errorsHashToArray: (errors: {}) => any[];
Convert an hash of errors into an array with errors in JSON-API format.
function hasMany
hasMany: { <K extends string | number | symbol>( type: K, options: RelationshipOptions<ModelRegistry[K]> & Sync ): Ember.ComputedProperty<SyncHasMany<ModelRegistry>>; <K extends string | number | symbol>( type: K, options?: RelationshipOptions<ModelRegistry> & Async ): Ember.ComputedProperty< AsyncHasMany<ModelRegistry>, Ember.Array<ModelRegistry> >;};
DS.hasMany
is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html).
function normalizeModelName
normalizeModelName: <K extends string | number | symbol>(modelName: K) => string;
This method normalizes a modelName into the format Ember Data uses internally.
class AbortError
class AbortError extends AdapterError {}
A
DS.AbortError
is used by an adapter to signal that a request to the external API was aborted. For example, this can occur if the user navigates away from the current page after a request to the external API has been initiated but before a response has been received.
class Adapter
class Adapter extends Ember.Object {}
An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the
store
.
property defaultSerializer
defaultSerializer: string;
If you would like your adapter to use a custom serializer you can set the
defaultSerializer
property to be the name of the custom serializer.
method createRecord
createRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, snapshot: Snapshot<K>) => RSVP.Promise<any>;
Implement this method in a subclass to handle the creation of new records.
method deleteRecord
deleteRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, snapshot: Snapshot<K>) => RSVP.Promise<any>;
Implement this method in a subclass to handle the deletion of a record.
method findAll
findAll: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, sinceToken: string, snapshotRecordArray: SnapshotRecordArray<K>) => RSVP.Promise<any>;
The
findAll()
method is used to retrieve all records for a given type.
method findMany
findMany: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, ids: any[], snapshots: any[]) => RSVP.Promise<any>;
The store will call
findMany
instead of multiplefindRecord
requests to find multiple records at once if coalesceFindRequests is true.
method findRecord
findRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, id: string, snapshot: Snapshot<K>) => RSVP.Promise<any>;
The
findRecord()
method is invoked when the store is asked for a record that has not previously been loaded. In response tofindRecord()
being called, you should query your persistence layer for a record with the given ID. ThefindRecord
method should return a promise that will resolve to a JavaScript object that will be normalized by the serializer.
method generateIdForRecord
generateIdForRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, inputProperties: {}) => string | number;
If the globally unique IDs for your records should be generated on the client, implement the
generateIdForRecord()
method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record'sprimaryKey
.
method groupRecordsForFindMany
groupRecordsForFindMany: (store: Store, snapshots: any[]) => any[];
Organize records into groups, each of which is to be passed to separate calls to
findMany
.
method query
query: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, query: {}, recordArray: AdapterPopulatedRecordArray<any>) => RSVP.Promise<any>;
This method is called when you call
query
on the store.
method queryRecord
queryRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, query: {}) => RSVP.Promise<any>;
The
queryRecord()
method is invoked when the store is asked for a single record through a query object.
method serialize
serialize: <K extends string | number | symbol>( snapshot: Snapshot<K>, options: {}) => {};
Proxies to the serializer's
serialize
method.
method shouldBackgroundReloadAll
shouldBackgroundReloadAll: <K extends string | number | symbol>( store: Store, snapshotRecordArray: SnapshotRecordArray<K>) => boolean;
This method is used by the store to determine if the store should reload a record array after the
store.findAll
method resolves with a cached record array.
method shouldBackgroundReloadRecord
shouldBackgroundReloadRecord: <K extends string | number | symbol>( store: Store, snapshot: Snapshot<K>) => boolean;
This method is used by the store to determine if the store should reload a record after the
store.findRecord
method resolves a cached record.
method shouldReloadAll
shouldReloadAll: <K extends string | number | symbol>( store: Store, snapshotRecordArray: SnapshotRecordArray<K>) => boolean;
This method is used by the store to determine if the store should reload all records from the adapter when records are requested by
store.findAll
.
method shouldReloadRecord
shouldReloadRecord: <K extends string | number | symbol>( store: Store, snapshot: Snapshot<K>) => boolean;
This method is used by the store to determine if the store should reload a record from the adapter when a record is requested by
store.findRecord
.
method updateRecord
updateRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, snapshot: Snapshot<K>) => RSVP.Promise<any>;
Implement this method in a subclass to handle the updating of a record.
class AdapterError
class AdapterError extends EmberError {}
A
DS.AdapterError
is used by an adapter to signal that an error occurred during a request to an external API. It indicates a generic error, and subclasses are used to indicate specific error states. The following subclasses are provided:
method extend
static extend: (options?: { message?: string }) => typeof AdapterError;
class AdapterPopulatedRecordArray
class AdapterPopulatedRecordArray<T> extends RecordArray<T> {}
Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the
AdapterPopulatedRecordArray
.
class BelongsToReference
class BelongsToReference {}
A BelongsToReference is a low level API that allows users and addon author to perform meta-operations on a belongs-to relationship.
method id
id: () => string;
The
id
of the record that this reference refers to. Together, thetype()
andid()
methods form a composite key for the identity map. This can be used to access the id of an async relationship without triggering a fetch that would normally happen if you attempted to userecord.get('relationship.id')
.
method link
link: () => string;
The link Ember Data will use to fetch or reload this belongs-to relationship.
method load
load: () => RSVP.Promise<any>;
Loads a record in a belongs to relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load.
method meta
meta: () => {};
The meta data for the belongs-to relationship.
method push
push: (objectOrPromise: {} | RSVP.Promise<any>) => RSVP.Promise<any>;
push
can be used to update the data in the relationship and Ember Data will treat the new data as the conanical value of this relationship on the backend.
method reload
reload: () => RSVP.Promise<any>;
Triggers a reload of the value in this relationship. If the remoteType is
"link"
Ember Data will use the relationship link to reload the relationship. Otherwise it will reload the record by its id.
method remoteType
remoteType: () => string;
This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id".
method value
value: () => Model | null;
value()
synchronously returns the current value of the belongs-to relationship. Unlikerecord.get('relationshipName')
, callingvalue()
on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always returnnull
.
class BooleanTransform
class BooleanTransform extends Transform<boolean> {}
The
DS.BooleanTransform
class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used whenboolean
is passed as the type parameter to the [DS.attr](../../data#method_attr) function.
class BuildURLMixin
class BuildURLMixin {}
WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 ## Using BuildURLMixin To use url building, include the mixin when extending an adapter, and call
buildURL
where needed. The default behaviour is designed for RESTAdapter. ### Exampleexport default DS.Adapter.extend(BuildURLMixin, {findRecord: function(store, type, id, snapshot) {var url = this.buildURL(type.modelName, id, snapshot, 'findRecord');return this.ajax(url, 'GET');}});### Attributes The
host
andnamespace
attributes will be used if defined, and are optional.
method buildQuery
buildQuery: <K extends string | number | symbol>( snapshot: Snapshot<K>) => Record<string, unknown>;
Used by
findAll
andfindRecord
to build the query'sdata
hash supplied to the ajax method.
method buildURL
buildURL: <K extends string | number | symbol>( modelName?: K, id?: string | any[] | {} | null, snapshot?: Snapshot<K> | any[] | null, requestType?: string, query?: {}) => string;
Builds a URL for a given type and optional ID.
method pathForType
pathForType: <K extends string | number | symbol>(modelName: K) => string;
Determines the pathname for a given type.
method urlForCreateRecord
urlForCreateRecord: <K extends string | number | symbol>( modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
record.save()
call when the record was created locally usingstore.createRecord()
.
method urlForDeleteRecord
urlForDeleteRecord: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
record.save()
call when the record has been deleted locally.
method urlForFindAll
urlForFindAll: <K extends string | number | symbol>( modelName: K, snapshot: SnapshotRecordArray<K>) => string;
Builds a URL for a
store.findAll(type)
call.
method urlForFindBelongsTo
urlForFindBelongsTo: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for fetching a async belongsTo relationship when a url is not provided by the server.
method urlForFindHasMany
urlForFindHasMany: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for fetching a async hasMany relationship when a url is not provided by the server.
method urlForFindMany
urlForFindMany: <K extends string | number | symbol>( ids: any[], modelName: K, snapshots: any[]) => string;
Builds a URL for coalesceing multiple
store.findRecord(type, id)
records into 1 request when the adapter'scoalesceFindRequests
property is true.
method urlForFindRecord
urlForFindRecord: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
store.findRecord(type, id)
call.
method urlForQuery
urlForQuery: <K extends string | number | symbol>( query: {}, modelName: K) => string;
Builds a URL for a
store.query(type, query)
call.
method urlForQueryRecord
urlForQueryRecord: <K extends string | number | symbol>( query: {}, modelName: K) => string;
Builds a URL for a
store.queryRecord(type, query)
call.
method urlForUpdateRecord
urlForUpdateRecord: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
record.save()
call when the record has been update locally.
class ConflictError
class ConflictError extends AdapterError {}
A
DS.ConflictError
equates to a HTTP409 Conflict
response status. It is used by an adapter to indicate that the request could not be processed because of a conflict in the request. An example scenario would be when creating a record with a client generated id but that id is already known to the external API.
class DateTransform
class DateTransform extends Transform<Date> {}
The
DS.DateTransform
class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used whendate
is passed as the type parameter to the [DS.attr](../../data#method_attr) function. It uses the [ISO 8601
](https://en.wikipedia.org/wiki/ISO_8601) standard.
class EmbeddedRecordsMixin
class EmbeddedRecordsMixin {}
## Using Embedded Records
method normalize
normalize: (typeClass: ModelSchema, hash: {}, prop: string) => {};
Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered
method removeEmbeddedForeignKey
removeEmbeddedForeignKey: <K extends string | number | symbol>( snapshot: Snapshot<K>, embeddedSnapshot: Snapshot<K>, relationship: {}, json: {}) => any;
When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship).
method serializeBelongsTo
serializeBelongsTo: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, relationship: {}) => any;
Serialize
belongsTo
relationship when it is configured as an embedded object.
method serializeHasMany
serializeHasMany: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, relationship: {}) => any;
Serializes
hasMany
relationships when it is configured as embedded objects.
class Errors
class Errors extends Ember.ArrayProxy<any> {}
property isEmpty
isEmpty: Ember.ComputedProperty<boolean>;
property length
length: Ember.ComputedProperty<number>;
Total number of errors.
property messages
messages: Ember.ComputedProperty<any[]>;
An array containing all of the error messages for this record. This is useful for displaying all errors to the user.
method add
add: (attribute: string, messages: any[] | string) => any;
DEPRECATED: Adds error messages to a given attribute and sends
becameInvalid
event to the record.
method clear
clear: () => any;
DEPRECATED: Removes all error messages and sends
becameValid
event to the record.
method errorsFor
errorsFor: (attribute: string) => any[];
Returns errors for a given attribute
method has
has: (attribute: string) => boolean;
Checks if there is error messages for the given attribute.
method registerHandlers
registerHandlers: ( target: {}, becameInvalid: Function, becameValid: Function) => any;
DEPRECATED: Register with target handler
method remove
remove: (attribute: string) => any;
DEPRECATED: Removes all error messages from the given attribute and sends
becameValid
event to the record if there no more errors left.
class FilteredRecordArray
class FilteredRecordArray<T> extends RecordArray<T> {}
Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array.
method filterFunction
filterFunction: (record: Model) => boolean;
The filterFunction is a function used to test records from the store to determine if they should be part of the record array.
class ForbiddenError
class ForbiddenError extends AdapterError {}
A
DS.ForbiddenError
equates to a HTTP403 Forbidden
response status. It is used by an adapter to signal that a request to the external API was valid but the server is refusing to respond to it. If authorization was provided and is valid, then the authenticated user does not have the necessary permissions for the request.
class HasManyReference
class HasManyReference<T> {}
A HasManyReference is a low level API that allows users and addon author to perform meta-operations on a has-many relationship.
method ids
ids: () => string[];
ids()
returns an array of the record ids in this relationship.
method link
link: () => string;
The link Ember Data will use to fetch or reload this has-many relationship.
method load
load: () => RSVP.Promise<any>;
Loads the relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load.
method meta
meta: () => {};
The meta data for the has-many relationship.
method push
push: (objectOrPromise: T[] | RSVP.Promise<T[]>) => ManyArray<T>;
push
can be used to update the data in the relationship and Ember Data will treat the new data as the canonical value of this relationship on the backend.
method reload
reload: () => RSVP.Promise<any>;
Reloads this has-many relationship.
method remoteType
remoteType: () => string;
This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id".
method value
value: () => ManyArray<T> | null;
value()
synchronously returns the current value of the has-many relationship. Unlikerecord.get('relationshipName')
, callingvalue()
on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always returnnull
.
class InvalidError
class InvalidError extends AdapterError {}
A
DS.InvalidError
is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with aDS.InvalidError
the record will transition to theinvalid
state and the errors will be set to theerrors
property on the record.
constructor
constructor(errors: any[]);
class JSONAPIAdapter
class JSONAPIAdapter extends RESTAdapter {}
The
JSONAPIAdapter
is the default adapter used by Ember Data. It is responsible for transforming the store's requests into HTTP requests that follow the [JSON API](http://jsonapi.org/format/) format.
class JSONAPISerializer
class JSONAPISerializer extends JSONSerializer {}
Ember Data 2.0 Serializer:
method keyForAttribute
keyForAttribute: (key: string, method: string) => string;
keyForAttribute
can be used to define rules for how to convert an attribute name in your model to a key in your JSON. By defaultJSONAPISerializer
follows the format used on the examples of http://jsonapi.org/format and uses dashes as the word separator in the JSON attribute keys.
method keyForRelationship
keyForRelationship: (key: string, typeClass: string, method: string) => string;
keyForRelationship
can be used to define a custom key when serializing and deserializing relationship properties. By defaultJSONAPISerializer
follows the format used on the examples of http://jsonapi.org/format and uses dashes as word separators in relationship properties.
method modelNameFromPayloadKey
modelNameFromPayloadKey: (key: string) => string;
Dasherizes and singularizes the model name in the payload to match the format Ember Data uses internally for the model name.
method modelNameFromPayloadType
modelNameFromPayloadType: (payloadType: string) => string;
modelNameFromPayloadType
can be used to change the mapping for a DS model name, taken from the value in the payload.
method payloadKeyFromModelName
payloadKeyFromModelName: <K extends string | number | symbol>( modelName: K) => string;
Converts the model name to a pluralized version of the model name.
method payloadTypeFromModelName
payloadTypeFromModelName: <K extends string | number | symbol>( modelName: K) => string;
payloadTypeFromModelName
can be used to change the mapping for the type in the payload, taken from the model name.
method pushPayload
pushPayload: (store: Store, payload: {}) => any;
class JSONSerializer
class JSONSerializer extends Serializer {}
Ember Data 2.0 Serializer:
property attrs
attrs: {};
The
attrs
object can be used to declare a simple mapping between property names onDS.Model
records and payload keys in the serialized JSON object representing the record. An object with the propertykey
can also be used to designate the attribute's key on the response payload.
property primaryKey
primaryKey: string;
The
primaryKey
is used when serializing and deserializing data. Ember Data always uses theid
property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override theprimaryKey
property to match theprimaryKey
of your external store.
method extractAttributes
extractAttributes: (modelClass: ModelSchema, resourceHash: {}) => {};
Returns the resource's attributes formatted as a JSON-API "attributes object".
method extractErrors
extractErrors: ( store: Store, typeClass: ModelSchema, payload: {}, id: string | number) => {};
extractErrors
is used to extract model errors when a call toDS.Model#save
fails with anInvalidError
. By default Ember Data expects error information to be located on theerrors
property of the payload object.
method extractId
extractId: (modelClass: {}, resourceHash: {}) => string;
Returns the resource's ID.
method extractMeta
extractMeta: (store: Store, modelClass: ModelSchema, payload: {}) => any;
extractMeta
is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on themeta
property of the payload object.
method extractPolymorphicRelationship
extractPolymorphicRelationship: ( relationshipModelName: {}, relationshipHash: {}, relationshipOptions: {}) => {};
Returns a polymorphic relationship formatted as a JSON-API "relationship object".
method extractRelationship
extractRelationship: (relationshipModelName: {}, relationshipHash: {}) => {};
Returns a relationship formatted as a JSON-API "relationship object".
method extractRelationships
extractRelationships: (modelClass: ModelSchema, resourceHash: {}) => {};
Returns the resource's relationships formatted as a JSON-API "relationships object".
method keyForAttribute
keyForAttribute: (key: string, method: string) => string;
keyForAttribute
can be used to define rules for how to convert an attribute name in your model to a key in your JSON.
method keyForLink
keyForLink: (key: string, kind: string) => string;
keyForLink
can be used to define a custom key when deserializing link properties.
method keyForRelationship
keyForRelationship: (key: string, typeClass: string, method: string) => string;
keyForRelationship
can be used to define a custom key when serializing and deserializing relationship properties. By defaultJSONSerializer
does not provide an implementation of this method.
method modelNameFromPayloadKey
modelNameFromPayloadKey: (key: string) => string;
method modelNameFromPayloadType
modelNameFromPayloadType: (type: string) => string;
method normalize
normalize: (typeClass: ModelSchema, hash: {}) => {};
Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do.
method normalizeArrayResponse
normalizeArrayResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeCreateRecordResponse
normalizeCreateRecordResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeDeleteRecordResponse
normalizeDeleteRecordResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeFindAllResponse
normalizeFindAllResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeFindBelongsToResponse
normalizeFindBelongsToResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeFindHasManyResponse
normalizeFindHasManyResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeFindManyResponse
normalizeFindManyResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeFindRecordResponse
normalizeFindRecordResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeQueryRecordResponse
normalizeQueryRecordResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeQueryResponse
normalizeQueryResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeResponse
normalizeResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
The
normalizeResponse
method is used to normalize a payload from the server to a JSON-API Document.
method normalizeSaveResponse
normalizeSaveResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeSingleResponse
normalizeSingleResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method normalizeUpdateRecordResponse
normalizeUpdateRecordResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
method serialize
serialize: <K extends string | number | symbol>( snapshot: Snapshot<K>, options: {}) => {};
Called when a record is saved in order to convert the record into JSON.
method serializeAttribute
serializeAttribute: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, key: string, attribute: {}) => any;
serializeAttribute
can be used to customize howDS.attr
properties are serialized
method serializeBelongsTo
serializeBelongsTo: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, relationship: {}) => any;
serializeBelongsTo
can be used to customize howDS.belongsTo
properties are serialized.
method serializeHasMany
serializeHasMany: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, relationship: {}) => any;
serializeHasMany
can be used to customize howDS.hasMany
properties are serialized.
method serializeId
serializeId: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, primaryKey: string) => any;
serializeId can be used to customize how id is serialized For example, your server may expect integer datatype of id
method serializeIntoHash
serializeIntoHash: <K extends string | number | symbol>( hash: {}, typeClass: ModelSchema<K>, snapshot: Snapshot<K>, options?: {}) => any;
You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. The hash property should be modified by reference.
method serializePolymorphicType
serializePolymorphicType: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, relationship: {}) => any;
You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if
{ polymorphic: true }
is pass as the second argument to theDS.belongsTo
function.
method shouldSerializeHasMany
shouldSerializeHasMany: <K extends string | number | symbol>( snapshot: Snapshot<K>, key: string, relationshipType: string) => boolean;
Check if the given hasMany relationship should be serialized
class ManyArray
class ManyArray<T> extends Ember.Object {}
property isLoaded
isLoaded: boolean;
The loading state of this array
property meta
meta: {};
Metadata associated with the request for async hasMany relationships.
method createRecord
createRecord: (inputProperties?: {}) => T;
Create a child record within the owner
method reload
reload: () => PromiseArray<T>;
Reloads all of the records in the manyArray. If the manyArray holds a relationship that was originally fetched using a links url Ember Data will revisit the original links url to repopulate the relationship.
method save
save: () => PromiseArray<T>;
Saves all of the records in the
ManyArray
.
class Model
class Model extends Ember.Object {}
The model class that all Ember Data records descend from. This is the public API of Ember Data models. If you are using Ember Data in your application, this is the class you should use. If you are working on Ember Data internals, you most likely want to be dealing with
InternalModel
property adapterError
adapterError: AdapterError;
This property holds the
DS.AdapterError
object with which last adapter operation was rejected.
property attributes
static attributes: Ember.ComputedProperty<Map<string, unknown>>;
A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property.
property dirtyType
dirtyType: Ember.ComputedProperty<string>;
If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are:
property errors
errors: Errors;
When the record is in the
invalid
state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys:
property fields
static fields: Ember.ComputedProperty<Map<string, unknown>>;
A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships.
property hasDirtyAttributes
hasDirtyAttributes: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in thedirty
state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted.
property id
id: string;
All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute.
property isDeleted
isDeleted: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in thedeleted
state and has been marked for deletion. WhenisDeleted
is true andhasDirtyAttributes
is true, the record is deleted locally but the deletion was not yet persisted. WhenisSaving
is true, the change is in-flight. When bothhasDirtyAttributes
andisSaving
are false, the change has persisted.
property isEmpty
isEmpty: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in theempty
state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to theloading
state if data needs to be fetched from the server or thecreated
state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record.
property isError
isError: boolean;
If
true
the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error.
property isLoaded
isLoaded: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in theloaded
state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of theloaded
state.
property isLoading
isLoading: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in theloading
state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data.
property isNew
isNew: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in thenew
state. A record will be in thenew
state when it has been created on the client and the adapter has not yet report that it was successfully saved.
property isReloading
isReloading: boolean;
If
true
the store is attempting to reload the record from the adapter.
property isSaving
isSaving: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in thesaving
state. A record enters the saving state whensave
is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend.
property isValid
isValid: Ember.ComputedProperty<boolean>;
If this property is
true
the record is in thevalid
state.
property modelName
static modelName: string | number | symbol;
Represents the model's class name as a string. This can be used to look up the model's class name through
DS.Store
's modelFor method.
property relatedTypes
static relatedTypes: Ember.ComputedProperty<Ember.NativeArray<string>>;
An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model.
property relationshipNames
static relationshipNames: Ember.ComputedProperty<{}>;
A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition:
property relationships
static relationships: Ember.ComputedProperty<Map<string, unknown>>;
The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type.
property relationshipsByName
static relationshipsByName: Ember.ComputedProperty<Map<string, unknown>>;
A map whose keys are the relationships of a model and whose values are relationship descriptors.
property store
store: Store;
A reference to DS.Store service instance.
property transformedAttributes
static transformedAttributes: Ember.ComputedProperty<Map<string, unknown>>;
A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type.
method becameError
becameError: () => void;
Fired when the record enters the error state.
method becameInvalid
becameInvalid: () => void;
Fired when the record becomes invalid.
method belongsTo
belongsTo: (name: RelationshipsFor<this>) => BelongsToReference;
Get the reference for the specified belongsTo relationship.
method changedAttributes
changedAttributes: () => ChangedAttributes;
Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array.
method deleteRecord
deleteRecord: () => void;
Marks the record as deleted but does not save it. You must call
save
afterwards if you want to persist it. You might use this method if you want to allow the user to stillrollbackAttributes()
after a delete was made.
method destroyRecord
destroyRecord: (options?: { adapterOptions?: object | undefined;}) => RSVP.Promise<this>;
Same as
deleteRecord
, but saves the record immediately.
method didCreate
didCreate: () => void;
Fired when a new record is commited to the server.
method didDelete
didDelete: () => void;
Fired when the record is deleted.
method didLoad
didLoad: () => void;
Fired when the record is loaded from the server.
method didUpdate
didUpdate: () => void;
Fired when the record is updated.
method eachAttribute
static eachAttribute: < Class extends typeof Model, M extends InstanceType<Class>>( this: Class, callback: (name: ModelKeys<M>, meta: AttributeMeta<M>) => void, binding?: any) => void;
Iterates through the attributes of the model, calling the passed function on each attribute.
method eachRelatedType
static eachRelatedType: ( callback: (name: string) => void, binding?: any) => void;
Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model.
method eachRelationship
static eachRelationship: <M extends Model = Model>( callback: (name: ModelKeys<M>, details: RelationshipMeta<M>) => void, binding?: any) => void;
Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor.
method eachTransformedAttribute
static eachTransformedAttribute: <Class extends typeof Model>( this: Class, callback: ( name: ModelKeys<InstanceType<Class>>, type: keyof TransformRegistry ) => void, binding?: any) => void;
Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type.
method hasMany
hasMany: (name: RelationshipsFor<this>) => HasManyReference<any>;
Get the reference for the specified hasMany relationship.
method inverseFor
static inverseFor: <K extends string | number | symbol>( name: K, store: Store) => {};
Find the relationship which is the inverse of the one asked for.
method ready
ready: () => void;
Fired when the record is ready to be interacted with, that is either loaded from the server or created locally.
method reload
reload: (options?: { adapterOptions?: object | undefined;}) => RSVP.Promise<this>;
Reload the record from the adapter.
method rollbackAttributes
rollbackAttributes: () => void;
If the model
hasDirtyAttributes
this function will discard any unsaved changes. If the modelisNew
it will be removed from the store.
method rolledBack
rolledBack: () => void;
Fired when the record is rolled back.
method save
save: (options?: { adapterOptions?: object | undefined }) => RSVP.Promise<this>;
Save the record and persist any changes to the record to an external source via the adapter.
method serialize
serialize: (options?: { includeId?: boolean | undefined }) => object;
Create a JSON representation of the record, using the serialization strategy of the store's adapter.
method toJSON
toJSON: (options?: { includeId?: boolean | undefined }) => object;
Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record.
method typeForRelationship
static typeForRelationship: <K extends string | number | symbol>( name: K, store: Store) => ModelRegistry;
For a given relationship name, returns the model type of the relationship.
method unloadRecord
unloadRecord: () => void;
Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection.
class NotFoundError
class NotFoundError extends AdapterError {}
A
DS.NotFoundError
equates to a HTTP404 Not Found
response status. It is used by an adapter to signal that a request to the external API was rejected because the resource could not be found on the API.
class NumberTransform
class NumberTransform extends Transform<number> {}
The
DS.NumberTransform
class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used whennumber
is passed as the type parameter to the [DS.attr](../../data#method_attr) function.
class PromiseArray
class PromiseArray<T> extends Ember.ArrayProxy<T> {}
class PromiseManyArray
class PromiseManyArray<T extends Model> extends PromiseArray< T, Ember.ArrayProxy<T>> {}
A PromiseManyArray is a PromiseArray that also proxies certain method calls to the underlying manyArray. Right now we proxy:
method createRecord
createRecord: (inputProperties?: {}) => T;
Create a child record within the owner
method reload
reload: () => PromiseManyArray<T>;
Reloads all of the records in the manyArray. If the manyArray holds a relationship that was originally fetched using a links url Ember Data will revisit the original links url to repopulate the relationship.
class PromiseObject
class PromiseObject<T> extends ObjectProxy<NonNullable<T>> {}
class RecordArray
class RecordArray<T> {}
property isLoaded
isLoaded: boolean;
The flag to signal a
RecordArray
is finished loading data.
property isUpdating
isUpdating: boolean;
The flag to signal a
RecordArray
is currently loading data.
property type
type: Ember.ComputedProperty<Model>;
The modelClass represented by this record array.
method save
save: () => PromiseArray<T>;
Saves all of the records in the
RecordArray
.
method update
update: () => PromiseArray<T>;
Used to get the latest version of all of the records in this array from the adapter.
class RecordReference
class RecordReference<T extends Model> {}
An RecordReference is a low level API that allows users and addon author to perform meta-operations on a record.
method id
id: () => string;
The
id
of the record that this reference refers to.
method load
load: () => PromiseObject<T>;
Triggers a fetch for the backing entity based on its
remoteType
(seeremoteType
definitions per reference type).
method push
push: (payload: RSVP.Promise<any> | {}) => PromiseObject<T>;
This API allows you to provide a reference with new data. The simplest usage of this API is similar to
store.push
: you provide a normalized hash of data and the object represented by the reference will update.
method reload
reload: () => PromiseObject<T>;
Reloads the record if it is already loaded. If the record is not loaded it will load the record via
store.findRecord
method remoteType
remoteType: () => string;
How the reference will be looked up when it is loaded: Currently this always return
identity
to signifying that a record will be loaded by thetype
andid
.
method value
value: () => T | null;
If the entity referred to by the reference is already loaded, it is present as
reference.value
. Otherwise the value returned by this function isnull
.
class RESTAdapter
class RESTAdapter extends Adapter implements BuildURLMixin {}
The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter.
method ajax
ajax: (url: string, type: string, options?: object) => RSVP.Promise<any>;
Takes a URL, an HTTP method and a hash of data, and makes an HTTP request.
method ajaxOptions
ajaxOptions: (url: string, type: string, options?: object) => object;
Generate ajax options
method buildQuery
buildQuery: <K extends string | number | symbol>( snapshot: Snapshot<K>) => Record<string, unknown>;
Used by
findAll
andfindRecord
to build the query'sdata
hash supplied to the ajax method.
method buildURL
buildURL: <K extends string | number | symbol>( modelName?: K, id?: string | any[] | {} | null, snapshot?: Snapshot<K> | any[] | null, requestType?: string, query?: {}) => string;
Builds a URL for a given type and optional ID.
method createRecord
createRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, snapshot: Snapshot<K>) => RSVP.Promise<any>;
Called by the store when a newly created record is saved via the
save
method on a model record instance.
method dataForRequest
dataForRequest: (params: {}) => {};
Get the data (body or query params) for a request.
method deleteRecord
deleteRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, snapshot: Snapshot<K>) => RSVP.Promise<any>;
Called by the store when a record is deleted.
method findAll
findAll: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, sinceToken: string, snapshotRecordArray: SnapshotRecordArray<K>) => RSVP.Promise<any>;
Called by the store in order to fetch a JSON array for all of the records for a given type.
method findBelongsTo
findBelongsTo: <K extends string | number | symbol>( store: Store, snapshot: Snapshot<K>, url: string) => RSVP.Promise<any>;
Called by the store in order to fetch the JSON for the unloaded record in a belongs-to relationship that was originally specified as a URL (inside of
links
).
method findHasMany
findHasMany: <K extends string | number | symbol>( store: Store, snapshot: Snapshot<K>, url: string, relationship: {}) => RSVP.Promise<any>;
Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of
links
).
method findMany
findMany: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, ids: any[], snapshots: any[]) => RSVP.Promise<any>;
Called by the store in order to fetch several records together if
coalesceFindRequests
is true
method findRecord
findRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, id: string, snapshot: Snapshot<K>) => RSVP.Promise<any>;
Called by the store in order to fetch the JSON for a given type and ID.
method groupRecordsForFindMany
groupRecordsForFindMany: (store: Store, snapshots: any[]) => any[];
Organize records into groups, each of which is to be passed to separate calls to
findMany
.
method handleResponse
handleResponse: ( status: number, headers: {}, payload: {}, requestData: {}) => {};
Takes an ajax response, and returns the json payload or an error.
method headersForRequest
headersForRequest: (params: {}) => {};
Get the headers for a request.
method isInvalid
isInvalid: (status: number, headers: {}, payload: {}) => boolean;
Default
handleResponse
implementation uses this hook to decide if the response is an invalid error.
method isSuccess
isSuccess: (status: number, headers: {}, payload: {}) => boolean;
Default
handleResponse
implementation uses this hook to decide if the response is a success.
method methodForRequest
methodForRequest: (params: {}) => string;
Get the HTTP method for a request.
method pathForType
pathForType: <K extends string | number | symbol>(modelName: K) => string;
Determines the pathname for a given type.
method query
query: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, query: {}) => RSVP.Promise<any>;
Called by the store in order to fetch a JSON array for the records that match a particular query.
method queryRecord
queryRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, query: {}) => RSVP.Promise<any>;
Called by the store in order to fetch a JSON object for the record that matches a particular query.
method sortQueryParams
sortQueryParams: (obj: {}) => {};
By default, the RESTAdapter will send the query params sorted alphabetically to the server.
method updateRecord
updateRecord: <K extends string | number | symbol>( store: Store, type: ModelSchema<K>, snapshot: Snapshot<K>) => RSVP.Promise<any>;
Called by the store when an existing record is saved via the
save
method on a model record instance.
method urlForCreateRecord
urlForCreateRecord: <K extends string | number | symbol>( modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
record.save()
call when the record was created locally usingstore.createRecord()
.
method urlForDeleteRecord
urlForDeleteRecord: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
record.save()
call when the record has been deleted locally.
method urlForFindAll
urlForFindAll: <K extends string | number | symbol>( modelName: K, snapshot: SnapshotRecordArray<K>) => string;
Builds a URL for a
store.findAll(type)
call.
method urlForFindBelongsTo
urlForFindBelongsTo: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for fetching a async belongsTo relationship when a url is not provided by the server.
method urlForFindHasMany
urlForFindHasMany: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for fetching a async hasMany relationship when a url is not provided by the server.
method urlForFindMany
urlForFindMany: <K extends string | number | symbol>( ids: any[], modelName: K, snapshots: any[]) => string;
Builds a URL for coalesceing multiple
store.findRecord(type, id)
records into 1 request when the adapter'scoalesceFindRequests
property is true.
method urlForFindRecord
urlForFindRecord: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
store.findRecord(type, id)
call.
method urlForQuery
urlForQuery: <K extends string | number | symbol>( query: {}, modelName: K) => string;
Builds a URL for a
store.query(type, query)
call.
method urlForQueryRecord
urlForQueryRecord: <K extends string | number | symbol>( query: {}, modelName: K) => string;
Builds a URL for a
store.queryRecord(type, query)
call.
method urlForRequest
urlForRequest: (params: {}) => string;
Get the URL for a request.
method urlForUpdateRecord
urlForUpdateRecord: <K extends string | number | symbol>( id: string, modelName: K, snapshot: Snapshot<K>) => string;
Builds a URL for a
record.save()
call when the record has been update locally.
class RESTSerializer
class RESTSerializer extends JSONSerializer {}
Normally, applications will use the
RESTSerializer
by implementing thenormalize
method.
method extractPolymorphicRelationship
extractPolymorphicRelationship: ( relationshipType: {}, relationshipHash: {}, relationshipOptions: {}) => {};
You can use this method to customize how a polymorphic relationship should be extracted.
method keyForPolymorphicType
keyForPolymorphicType: ( key: string, typeClass: string, method: string) => string;
keyForPolymorphicType
can be used to define a custom key when serializing and deserializing a polymorphic type. By default, the returned key is${key}Type
.
method modelNameFromPayloadKey
modelNameFromPayloadKey: (key: string) => string;
This method is used to convert each JSON root key in the payload into a modelName that it can use to look up the appropriate model for that part of the payload.
method modelNameFromPayloadType
modelNameFromPayloadType: (payloadType: string) => string;
modelNameFromPayloadType
can be used to change the mapping for a DS model name, taken from the value in the payload.
method normalize
normalize: (modelClass: ModelSchema, resourceHash: {}, prop?: string) => {};
Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do.
method payloadKeyFromModelName
payloadKeyFromModelName: <K extends string | number | symbol>( modelName: K) => string;
You can use
payloadKeyFromModelName
to override the root key for an outgoing request. By default, the RESTSerializer returns a camelized version of the model's name.
method payloadTypeFromModelName
payloadTypeFromModelName: <K extends string | number | symbol>( modelName: K) => string;
payloadTypeFromModelName
can be used to change the mapping for the type in the payload, taken from the model name.
method pushPayload
pushPayload: (store: Store, payload: {}) => any;
This method allows you to push a payload containing top-level collections of records organized per type.
method serialize
serialize: <K extends string | number | symbol>( snapshot: Snapshot<K>, options: {}) => {};
Called when a record is saved in order to convert the record into JSON.
method serializeIntoHash
serializeIntoHash: <K extends string | number | symbol>( hash: {}, typeClass: ModelSchema<K>, snapshot: Snapshot<K>, options?: {}) => any;
You can use this method to customize the root keys serialized into the JSON. The hash property should be modified by reference (possibly using something like _.extend) By default the REST Serializer sends the modelName of a model, which is a camelized version of the name.
method serializePolymorphicType
serializePolymorphicType: <K extends string | number | symbol>( snapshot: Snapshot<K>, json: {}, relationship: {}) => any;
You can use this method to customize how polymorphic objects are serialized. By default the REST Serializer creates the key by appending
Type
to the attribute and value from the model's camelcased model name.
class RootState
class RootState {}
### State
class Serializer
class Serializer extends Ember.Object {}
DS.Serializer
is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is:
property store
store: Store;
The
store
property is the application'sstore
that contains all records. It can be used to look up serializers for other model types that may be nested inside the payload response.
method normalize
normalize: (typeClass: ModelSchema, hash: {}) => {};
The
normalize
method is used to convert a payload received from your external data source into the normalized formstore.push()
expects. You should override this method, munge the hash and return the normalized payload.
method normalizeResponse
normalizeResponse: ( store: Store, primaryModelClass: ModelSchema, payload: {}, id: string | number, requestType: string) => {};
The
normalizeResponse
method is used to normalize a payload from the server to a JSON-API Document.
method serialize
serialize: <K extends string | number | symbol>( snapshot: Snapshot<K>, options: {}) => {};
The
serialize
method is used when a record is saved in order to convert the record into the form that your external data source expects.
class ServerError
class ServerError extends AdapterError {}
A
DS.ServerError
equates to a HTTP500 Internal Server Error
response status. It is used by the adapter to indicate that a request has failed because of an error in the external API.
class Snapshot
class Snapshot<K extends keyof ModelRegistry = keyof ModelRegistry> {}
property adapterOptions
adapterOptions: Record<string, unknown>;
A hash of adapter options
property id
id: string;
The id of the snapshot's underlying record
property modelName
modelName: string | number | symbol;
The name of the type of the underlying record for this snapshot, as a string.
property record
record: ModelRegistry;
The underlying record for this snapshot. Can be used to access methods and properties defined on the record.
property type
type: ModelRegistry;
The type of the underlying record for this snapshot, as a DS.Model.
method attr
attr: <L extends string | number | symbol>(keyName: L) => ModelRegistry;
Returns the value of an attribute.
method attributes
attributes: () => { [x: string]: ModelRegistry };
Returns all attributes and their corresponding values.
method belongsTo
belongsTo: { <L extends string | number | symbol>(keyName: L, options?: {}): | Snapshot | null | undefined; <L extends string | number | symbol>( keyName: L, options: { id: true } ): string;};
Returns the current value of a belongsTo relationship.
method changedAttributes
changedAttributes: () => Partial<{ [x: string]: ModelRegistry }>;
Returns all changed attributes and their old and new values.
method eachAttribute
eachAttribute: <M extends ModelRegistry>( callback: (key: ModelKeys<M>, meta: AttributeMeta<M>) => void, binding?: {}) => void;
Iterates through all the attributes of the model, calling the passed function on each attribute.
method eachRelationship
eachRelationship: <M extends ModelRegistry>( callback: (key: ModelKeys<M>, meta: RelationshipMeta<M>) => void, binding?: {}) => void;
Iterates through all the relationships of the model, calling the passed function on each relationship.
method hasMany
hasMany: { <L extends string | number | symbol>(keyName: L, options?: { ids: false }): | Snapshot[] | undefined; <L extends string | number | symbol>( keyName: L, options: { ids: true } ): string[];};
Returns the current value of a hasMany relationship.
method serialize
serialize: <O extends object>(options: O) => object;
Serializes the snapshot using the serializer for the model.
class SnapshotRecordArray
class SnapshotRecordArray<K extends keyof ModelRegistry> {}
property adapterOptions
adapterOptions: {};
A hash of adapter options passed into the store method for this request.
property include
include: string | any[];
The relationships to include for this request.
property length
length: number;
Number of records in the array
property meta
meta: {};
Meta objects for the record array.
property type
type: ModelRegistry;
The type of the underlying records for the snapshots in the array, as a DS.Model
method snapshots
snapshots: () => Snapshot[];
Get snapshots of the underlying record array
class Store
class Store extends Ember.Service {}
The store contains all of the data for records loaded from the server. It is also responsible for creating instances of
DS.Model
that wrap the individual data for a record, so that they can be bound to in your Handlebars templates.
property adapter
adapter: string;
The default adapter to use to communicate to a backend server or other persistence layer. This will be overridden by an application adapter if present.
method adapterFor
adapterFor: <K extends string | number | symbol>( modelName: K) => AdapterRegistry;
Returns an instance of the adapter for a given type. For example,
adapterFor('person')
will return an instance ofApp.PersonAdapter
.
method createRecord
createRecord: <K extends string | number | symbol>( modelName: K, inputProperties?: {}) => ModelRegistry;
Create a new record in the current store. The properties passed to this method are set on the newly created record.
method deleteRecord
deleteRecord: (record: Model) => void;
For symmetry, a record can be deleted via the store.
method findAll
findAll: <K extends string | number | symbol>( modelName: K, options?: { reload?: boolean | undefined; backgroundReload?: boolean | undefined; include?: string | undefined; adapterOptions?: any; }) => PromiseArray<ModelRegistry[K], Ember.ArrayProxy<ModelRegistry[K]>>;
findAll
asks the adapter'sfindAll
method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them.
method findRecord
findRecord: <K extends string | number | symbol>( modelName: K, id: string | number, options?: {}) => PromiseObject<ModelRegistry[K]>;
This method returns a record for a given type and id combination.
method getReference
getReference: <K extends string | number | symbol>( modelName: K, id: string | number) => RecordReference<ModelRegistry[K]>;
Get the reference for the specified record.
method hasRecordForId
hasRecordForId: <K extends string | number | symbol>( modelName: K, id: string | number) => boolean;
This method returns true if a record for a given modelName and id is already loaded in the store. Use this function to know beforehand if a findRecord() will result in a request or that it will be a cache hit.
method modelFor
modelFor: <K extends string | number | symbol>(modelName: K) => ModelRegistry;
Returns the model class for the particular
modelName
.
method normalize
normalize: <K extends string | number | symbol>(modelName: K, payload: {}) => {};
normalize
converts a json payload into the normalized form that [push](#method_push) expects.
method peekAll
peekAll: <K extends string | number | symbol>( modelName: K) => RecordArray<ModelRegistry[K]>;
This method returns a filtered array that contains all of the known records for a given type in the store.
method peekRecord
peekRecord: <K extends string | number | symbol>( modelName: K, id: string | number) => ModelRegistry[K] | null;
Get a record by a given type and ID without triggering a fetch.
method push
push: (data: {}) => Model | any[];
Push some data for a given type into the store.
method pushPayload
pushPayload: { <K extends string | number | symbol>(modelName: K, inputPayload: {}): any; (inputPayload: {}): any;};
Push some raw data into the store.
method query
query: <K extends string | number | symbol>( modelName: K, query: object, options?: { adapterOptions?: object | undefined }) => PromiseArray< ModelRegistry[K], AdapterPopulatedRecordArray<ModelRegistry[K]>>;
This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application.
method queryRecord
queryRecord: <K extends string | number | symbol>( modelName: K, query: object, options?: { adapterOptions?: object | undefined }) => RSVP.Promise<ModelRegistry>;
This method makes a request for one record, where the
id
is not known beforehand (if theid
is known, use [findRecord
](#method_findRecord) instead).
method recordIsLoaded
recordIsLoaded: <K extends string | number | symbol>( modelName: K, id: string) => boolean;
DEPRECATED: This method has been deprecated and is an alias for store.hasRecordForId, which should be used instead.
method serializerFor
serializerFor: <K extends string | number | symbol>( modelName: K) => SerializerRegistry;
Returns an instance of the serializer for a given type. For example,
serializerFor('person')
will return an instance ofApp.PersonSerializer
.
method unloadAll
unloadAll: <K extends string | number | symbol>(modelName?: K) => void;
This method unloads all records in the store. It schedules unloading to happen during the next run loop.
method unloadRecord
unloadRecord: (record: Model) => void;
For symmetry, a record can be unloaded via the store. This will cause the record to be destroyed and freed up for garbage collection.
class StringTransform
class StringTransform extends Transform<string> {}
The
DS.StringTransform
class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used whenstring
is passed as the type parameter to the [DS.attr](../../data#method_attr) function.
class TimeoutError
class TimeoutError extends AdapterError {}
A
DS.TimeoutError
is used by an adapter to signal that a request to the external API has timed out. I.e. no response was received from the external API within an allowed time period.
class Transform
class Transform<Deserialized = any, Serialized = any> extends Ember.Object {}
The
DS.Transform
class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. SubclassingDS.Transform
is useful for creating custom attributes. All subclasses ofDS.Transform
must implement aserialize
and adeserialize
method.
method deserialize
deserialize: ( serialized: Serialized, options: AttrOptions<Deserialized>) => Deserialized;
When given a serialize value from a JSON object this method must return the deserialized value for the record attribute.
method serialize
serialize: ( deserialized: Deserialized, options: AttrOptions<Deserialized>) => Serialized;
When given a deserialized value from a record attribute this method must return the serialized value.
class UnauthorizedError
class UnauthorizedError extends AdapterError {}
A
DS.UnauthorizedError
equates to a HTTP401 Unauthorized
response status. It is used by an adapter to signal that a request to the external API was rejected because authorization is required and has failed or has not yet been provided.
interface Adapter
interface Adapter {}
property coalesceFindRequests
coalesceFindRequests: boolean;
By default the store will try to coalesce all
fetchRecord
calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false.
interface AttrOptions
interface AttrOptions<T> {}
property allowNull
allowNull?: boolean | undefined;
property defaultValue
defaultValue?: T extends Exclude<object, null> ? () => T : T | (() => T) | null | undefined;
index signature
[key: string]: unknown;
interface Errors
interface Errors extends Ember.Enumerable<any>, Evented {}
Holds validation errors for a given record, organized by attribute names.
interface ManyArray
interface ManyArray<T> extends Ember.MutableArray<T>, Evented {}
A
ManyArray
is aMutableArray
that represents the contents of a has-many relationship.
interface PromiseArray
interface PromiseArray< T, ArrayType extends Ember.ArrayProxy<T>['content'] = Ember.Array<T>> extends Ember.ArrayProxy<T>, PromiseProxyMixin<ArrayType> {}
A
PromiseArray
is an object that acts like both anEmber.Array
and a promise. When the promise is resolved the resulting value will be set to thePromiseArray
'scontent
property. This makes it easy to create data bindings with thePromiseArray
that will be updated when the promise resolves.
interface PromiseObject
interface PromiseObject<T extends object | null> extends PromiseProxyMixin<T> {}
A
PromiseObject
is an object that acts like both anEmber.Object
and a promise. When the promise is resolved, then the resulting value will be set to thePromiseObject
'scontent
property. This makes it easy to create data bindings with thePromiseObject
that will be updated when the promise resolves.
interface RecordArray
interface RecordArray<T> extends Ember.ArrayProxy<T>, Evented {}
A record array is an array that contains records of a certain modelName. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of
DS.RecordArray
or its subclasses will be returned by your application's store in response to queries.
interface RelationshipOptions
interface RelationshipOptions<M extends Model> {}
property as
as?: string;
property async
async?: boolean | undefined;
property inverse
inverse?: RelationshipsFor<M> | null | undefined;
property polymorphic
polymorphic?: boolean | undefined;
index signature
[key: string]: unknown;
interface RESTAdapter
interface RESTAdapter {}
property headers
headers: {};
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the
RESTAdapter
'sheaders
object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization).
property host
host: string;
An adapter can target other hosts by setting the
host
property.
property namespace
namespace: string;
Endpoint paths can be prefixed with a
namespace
by setting the namespace property on the adapter:
type AsyncBelongsTo
type AsyncBelongsTo<T extends Model | null> = PromiseObject<T>;
type AsyncHasMany
type AsyncHasMany<T extends Model> = PromiseManyArray<T>;
type SyncHasMany
type SyncHasMany<T extends Model> = ManyArray<T>;
type TransformType
type TransformType<K extends keyof TransformRegistry> = TransformRegistry[K] extends Transform ? ReturnType<TransformRegistry[K]['deserialize']> : TransformRegistry[K];
Package Files (1)
Dependencies (4)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@types/ember-data
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@types/ember-data)
- HTML<a href="https://www.jsdocs.io/package/@types/ember-data"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5380 ms. - Missing or incorrect documentation? Open an issue for this package.