Documentation / @ember-data/adapter / rest / default
Defined in: packages/adapter/src/rest.ts:293
⚠️ This is LEGACY documentation for a feature that is no longer encouraged to be used. If starting a new app or thinking of implementing a new adapter, consider writing a Handler instead to be used with the RequestManager
The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR.
This adapter is designed around the idea that the JSON exchanged with the server should be conventional. It builds URLs in a manner that follows the structure of most common REST-style web services.
Success and failure
The REST adapter will consider a success any response with a status code of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other status code will be considered a failure.
On success, the request promise will be resolved with the full response payload.
Failed responses with status code 422 ("Unprocessable Entity") will be considered "invalid". The response will be discarded, except for the errors
key. The request promise will be rejected with a InvalidError
. This error object will encapsulate the saved errors
value.
Any other status codes will be treated as an "adapter error". The request promise will be rejected, similarly to the "invalid" case, but with an instance of AdapterError
instead.
JSON Structure
The REST adapter expects the JSON returned from your server to follow these conventions.
Object Root
The JSON payload should be an object that contains the record inside a root property. For example, in response to a GET
request for /posts/1
, the JSON should look like this:
{
"posts": {
"id": 1,
"title": "I'm Running to Reform the W3C",
"author": "Yehuda Katz"
}
}
Similarly, in response to a GET
request for /posts
, the JSON should look like this:
{
"posts": [
{
"id": 1,
"title": "I'm Running to Reform the W3C",
"author": "Yehuda Katz"
},
{
"id": 2,
"title": "Rails is omakase",
"author": "D2H"
}
]
}
Note that the object root can be pluralized for both a single-object response and an array response: the REST adapter is not strict on this. Further, if the HTTP server responds to a GET
request to /posts/1
(e.g. the response to a findRecord
query) with more than one object in the array, Ember Data will only display the object with the matching ID.
Conventional Names
Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models.
For example, if you have a Person
model:
import Model, { attr } from '@ember-data/model';
export default Model.extend({
firstName: attr('string'),
lastName: attr('string'),
occupation: attr('string')
});
The JSON returned should look like this:
{
"people": {
"id": 5,
"firstName": "Zaphod",
"lastName": "Beeblebrox",
"occupation": "President"
}
}
Relationships
Relationships are usually represented by ids to the record in the relationship. The related records can then be sideloaded in the response under a key for the type.
{
"posts": {
"id": 5,
"title": "I'm Running to Reform the W3C",
"author": "Yehuda Katz",
"comments": [1, 2]
},
"comments": [{
"id": 1,
"author": "User 1",
"message": "First!",
}, {
"id": 2,
"author": "User 2",
"message": "Good Luck!",
}]
}
If the records in the relationship are not known when the response is serialized it's also possible to represent the relationship as a URL using the links
key in the response. Ember Data will fetch this URL to resolve the relationship when it is accessed for the first time.
{
"posts": {
"id": 5,
"title": "I'm Running to Reform the W3C",
"author": "Yehuda Katz",
"links": {
"comments": "/posts/5/comments"
}
}
}
Errors
If a response is considered a failure, the JSON payload is expected to include a top-level key errors
, detailing any specific issues. For example:
{
"errors": {
"msg": "Something went wrong"
}
}
This adapter does not make any assumptions as to the format of the errors
object. It will simply be passed along as is, wrapped in an instance of InvalidError
or AdapterError
. The serializer can interpret it afterwards.
Customization
Endpoint path customization
Endpoint paths can be prefixed with a namespace
by setting the namespace property on the adapter:
import RESTAdapter from '@ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
namespace = 'api/1';
}
Requests for the Person
model would now target /api/1/people/1
.
Host customization
An adapter can target other hosts by setting the host
property.
import RESTAdapter from '@ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
host = 'https://api.example.com';
}
Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the RESTAdapter
's headers
object and EmberData will send them along with each ajax request.
import RESTAdapter from '@ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
get headers() {
return {
'API_KEY': 'secret key',
'ANOTHER_HEADER': 'Some header value'
};
}
}
RESTAdapter
Uses
BuildURLMixin
Extends
default
<this
>.MixtBuildURLMixin
Extended by
Constructors
Constructor
new default(owner?): RESTAdapter;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:8
Parameters
owner?
Owner
Returns
RESTAdapter
Inherited from
Properties
_coalesceFindRequests
_coalesceFindRequests: boolean;
Defined in: packages/adapter/src/rest.ts:295
Overrides
_defaultContentType
_defaultContentType: string = 'application/json; charset=utf-8';
Defined in: packages/adapter/src/rest.ts:309
_fastboot
_fastboot: FastBoot;
Defined in: packages/adapter/src/rest.ts:294
concatenatedProperties?
optional concatenatedProperties: string | string[];
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:655
Inherited from
default
.concatenatedProperties
headers
headers: undefined | Record<string, unknown>;
Defined in: packages/adapter/src/rest.ts:504
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the RESTAdapter
's headers
object and Ember Data will send them along with each ajax request. For dynamic headers see headers customization.
import RESTAdapter from '@ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
get headers() {
return {
'API_KEY': 'secret key',
'ANOTHER_HEADER': 'Some header value'
};
}
}
host
host: null | string;
Defined in: packages/adapter/src/rest.ts:296
maxURLLength
maxURLLength: number = 2048;
Defined in: packages/adapter/src/rest.ts:860
mergedProperties?
optional mergedProperties: unknown[];
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:656
Inherited from
namespace
namespace: null | string;
Defined in: packages/adapter/src/rest.ts:297
store
store: default;
Defined in: packages/adapter/src/index.ts:257
Inherited from
useFetch
useFetch: boolean = true;
Defined in: packages/adapter/src/rest.ts:307
This property allows ajax to still be used instead when false
.
Default
true
@public
_lazyInjections()?
readonly static optional _lazyInjections: () => void;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:654
Returns
void
Inherited from
_onLookup()?
readonly static optional _onLookup: (debugContainerKey) => void;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:653
Parameters
debugContainerKey
string
Returns
void
Inherited from
[INIT_FACTORY]?
static optional [INIT_FACTORY]: null;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/mixin.d.ts:116
Inherited from
isClass
readonly static isClass: boolean;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:651
Inherited from
isMethod
readonly static isMethod: boolean;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:652
Inherited from
PrototypeMixin
static PrototypeMixin: any;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:647
Inherited from
superclass
static superclass: any;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:648
Inherited from
Accessors
_debugContainerKey
Get Signature
get _debugContainerKey(): false | `${string}:${string}`;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/index.d.ts:34
Returns
false
| `${string}:${string}`
Inherited from
coalesceFindRequests
Get Signature
get coalesceFindRequests(): boolean;
Defined in: packages/adapter/src/rest.ts:431
By default the RESTAdapter will send each find request coming from a store.find
or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop.
For example, if you have an initial payload of:
{
post: {
id: 1,
comments: [1, 2]
}
}
By default calling post.comments
will trigger the following requests(assuming the comments haven't been loaded before):
GET /comments/1
GET /comments/2
If you set coalesceFindRequests to true
it will instead trigger the following request:
GET /comments?ids[]=1&ids[]=2
Setting coalesceFindRequests to true
also works for store.find
requests and belongsTo
relationships accessed within the same runloop. If you set coalesceFindRequests: true
store.findRecord('comment', 1);
store.findRecord('comment', 2);
will also send a request to: GET /comments?ids[]=1&ids[]=2
Note: Requests coalescing rely on URL building strategy. So if you override buildURL
in your app groupRecordsForFindMany
more likely should be overridden as well in order for coalescing to work.
Returns
boolean
Set Signature
set coalesceFindRequests(value): void;
Defined in: packages/adapter/src/rest.ts:439
By default the store will try to coalesce all findRecord
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.
Parameters
value
boolean
Returns
void
Optional
If your adapter implements findMany
, setting this to true
will cause findRecord
requests triggered within the same runloop
to be coalesced into one or more calls to adapter.findMany
. The number of calls made and the records contained in each call can be tuned by your adapter's groupRecordsForHasMany
method.
Implementing coalescing using this flag and the associated methods does not always offer the right level of correctness, timing control or granularity. If your application would be better suited coalescing across multiple types, coalescing for longer than a single runloop, or with a more custom request structure, coalescing within your application adapter may prove more effective.
Overrides
fastboot
Get Signature
get fastboot(): FastBoot;
Defined in: packages/adapter/src/rest.ts:312
Returns
FastBoot
Set Signature
set fastboot(value): void;
Defined in: packages/adapter/src/rest.ts:322
Parameters
value
FastBoot
Returns
void
isDestroyed
Get Signature
get isDestroyed(): boolean;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:272
Destroyed object property flag.
if this property is true
the observers and bindings were already removed by the effect of calling the destroy()
method.
Default
false
@public
Returns
boolean
Set Signature
set isDestroyed(_value): void;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:273
Parameters
_value
boolean
Returns
void
Inherited from
isDestroying
Get Signature
get isDestroying(): boolean;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:284
Destruction scheduled flag. The destroy()
method has been called.
The object stays intact until the end of the run loop at which point the isDestroyed
flag is set.
Default
false
@public
Returns
boolean
Set Signature
set isDestroying(_value): void;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:285
Parameters
_value
boolean
Returns
void
Inherited from
Methods
_ajax()
_ajax(options): void;
Defined in: packages/adapter/src/rest.ts:1061
Parameters
options
FetchRequestInit
| JQueryRequestInit
Returns
void
_ajaxURL()
_ajaxURL(url): string;
Defined in: packages/adapter/src/rest.ts:1125
Parameters
url
string
Returns
string
_buildURL()
_buildURL(
this,
modelName,
id?): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:90
Parameters
this
MixtBuildURLMixin
modelName
undefined
| null
| string
id?
null
| string
Returns
string
_fetchRequest()
_fetchRequest(options): Promise<Response>;
Defined in: packages/adapter/src/rest.ts:1055
Parameters
options
Returns
Promise
<Response
>
_stripIDFromURL()
_stripIDFromURL(store, snapshot): string;
Defined in: packages/adapter/src/rest.ts:832
Parameters
store
snapshot
Snapshot
Returns
string
addObserver()
Call Signature
addObserver<Target>(
key,
target,
method): this;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:333
Adds an observer on a property.
This is the core method used to register an observer for a property.
Once you call this method, any time the key's value is set, your observer will be notified. Note that the observers are triggered any time the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that.
There are two common invocation patterns for .addObserver()
:
- Passing two arguments:
- the name of the property to observe (as a string)
- the function to invoke (an actual function)
- Passing three arguments:
- the name of the property to observe (as a string)
- the target object (will be used to look up and invoke a function on)
- the name of the function to invoke on the target object (as a string).
import Component from '@ember/component';
export default Component.extend({
init() {
this._super(...arguments);
// the following are equivalent:
// using three arguments
this.addObserver('foo', this, 'fooDidChange');
// using two arguments
this.addObserver('foo', (...args) => {
this.fooDidChange(...args);
});
},
fooDidChange() {
// your custom logic code
}
});
Observer Methods
Observer methods have the following signature:
import Component from '@ember/component';
export default Component.extend({
init() {
this._super(...arguments);
this.addObserver('foo', this, 'fooDidChange');
},
fooDidChange(sender, key, value, rev) {
// your code
}
});
The sender
is the object that changed. The key
is the property that changes. The value
property is currently reserved and unused. The rev
is the last property revision of the object when it changed, which you can use to detect if the key value has really changed or not.
Usually you will not need the value or revision parameters at the end. In this case, it is common to write observer methods that take only a sender and key value as parameters or, if you aren't interested in any of these values, to write an observer that has no parameters at all.
Type Parameters
Target
Target
Parameters
key
keyof RESTAdapter
The key to observe
target
Target
The target object to invoke
method
ObserverMethod
<Target
, RESTAdapter
>
The method to invoke
Returns
this
Method
addObserver
Inherited from
Call Signature
addObserver(key, method): this;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:338
Parameters
key
keyof RESTAdapter
method
ObserverMethod
<RESTAdapter
, RESTAdapter
>
Returns
this
Inherited from
buildQuery()
buildQuery(snapshot): QueryState;
Defined in: packages/adapter/src/rest.ts:1242
Used by findAll
and findRecord
to build the query's data
hash supplied to the ajax method.
Parameters
snapshot
Snapshot
<unknown
> | SnapshotRecordArray
Returns
Since
2.5.0
buildURL()
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:17
Parameters
this
MixtBuildURLMixin
modelName
string
id
string
snapshot
Snapshot
requestType
"findRecord"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:24
Parameters
this
MixtBuildURLMixin
modelName
string
id
null
snapshot
SnapshotRecordArray
requestType
"findAll"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType,
query): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:31
Parameters
this
MixtBuildURLMixin
modelName
string
id
null
snapshot
null
requestType
"query"
query
Record
<string
, unknown
>
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType,
query): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:39
Parameters
this
MixtBuildURLMixin
modelName
string
id
null
snapshot
null
requestType
"queryRecord"
query
Record
<string
, unknown
>
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:47
Parameters
this
MixtBuildURLMixin
modelName
string
id
string
[]
snapshot
Snapshot
<unknown
>[]
requestType
"findMany"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:54
Parameters
this
MixtBuildURLMixin
modelName
string
id
string
snapshot
Snapshot
requestType
"findHasMany"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:61
Parameters
this
MixtBuildURLMixin
modelName
string
id
string
snapshot
Snapshot
requestType
"findBelongsTo"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:68
Parameters
this
MixtBuildURLMixin
modelName
string
id
null
| string
snapshot
Snapshot
requestType
"createRecord"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:75
Parameters
this
MixtBuildURLMixin
modelName
string
id
string
snapshot
Snapshot
requestType
"updateRecord"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot,
requestType): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:82
Parameters
this
MixtBuildURLMixin
modelName
string
id
string
snapshot
Snapshot
requestType
"deleteRecord"
Returns
string
Call Signature
buildURL(
this,
modelName,
id,
snapshot): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:89
Parameters
this
MixtBuildURLMixin
modelName
string
id
string
snapshot
Snapshot
Returns
string
cacheFor()
cacheFor<K>(key): unknown;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:413
Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily.
Type Parameters
K
K
extends keyof RESTAdapter
Parameters
key
K
Returns
unknown
The cached value of the computed property, if any
Method
cacheFor
Inherited from
createRecord()
createRecord(
store,
type,
snapshot): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:779
Called by the store when a newly created record is saved via the save
method on a model record instance.
The createRecord
method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by buildURL
.
See serialize
for information on how to customize the serialized form of a record.
Parameters
store
type
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Overrides
decrementProperty()
decrementProperty(keyName, decrement?): number;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:387
Set the value of a property to the current value minus some amount.
player.decrementProperty('lives');
orc.decrementProperty('health', 5);
Parameters
keyName
keyof RESTAdapter
The name of the property to decrement
decrement?
number
The amount to decrement by. Defaults to 1
Returns
number
The new property value
Method
decrementProperty
Inherited from
deleteRecord()
deleteRecord(
store,
schema,
snapshot): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:824
Called by the store when a record is deleted.
The deleteRecord
method makes an Ajax (HTTP DELETE) request to a URL computed by buildURL
.
Parameters
store
schema
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Overrides
destroy()
destroy(): this;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:300
Destroys an object by setting the isDestroyed
flag and removing its metadata, which effectively destroys observers and bindings.
If you try to set a property on a destroyed object, an exception will be raised.
Note that destruction is scheduled for the end of the run loop and does not happen immediately. It will set an isDestroying flag immediately.
Returns
this
receiver
Method
destroy
Inherited from
findAll()
findAll(
store,
type,
sinceToken,
snapshotRecordArray): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:544
Called by the store in order to fetch a JSON array for all of the records for a given type.
The findAll
method makes an Ajax (HTTP GET) request to a URL computed by buildURL
, and returns a promise for the resulting payload.
Parameters
store
type
sinceToken
null
snapshotRecordArray
SnapshotRecordArray
Returns
Promise
<AdapterPayload
>
promise
Overrides
findBelongsTo()
findBelongsTo(
store,
snapshot,
url,
relationship): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:751
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
).
For example, if your original payload looks like this:
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
This method will be called with the parent record and /people/1/group
.
The findBelongsTo
method will make an Ajax (HTTP GET) request to the originally specified URL.
The format of your links
value will influence the final request URL via the urlPrefix
method:
Links beginning with
//
,http://
,https://
, will be used as is, with no further manipulation.Links beginning with a single
/
will have the current adapter'shost
value prepended to it.Links with no beginning
/
will have a parentURL prepended to it, via the current adapter'sbuildURL
.
Parameters
store
snapshot
Snapshot
url
string
relationship
any
meta object describing the relationship
Returns
Promise
<AdapterPayload
>
promise
findHasMany()
findHasMany(
store,
snapshot,
url,
relationship): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:697
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
).
For example, if your original payload looks like this:
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
This method will be called with the parent record and /posts/1/comments
.
The findHasMany
method will make an Ajax (HTTP GET) request to the originally specified URL.
The format of your links
value will influence the final request URL via the urlPrefix
method:
Links beginning with
//
,http://
,https://
, will be used as is, with no further manipulation.Links beginning with a single
/
will have the current adapter'shost
value prepended to it.Links with no beginning
/
will have a parentURL prepended to it, via the current adapter'sbuildURL
.
Parameters
store
snapshot
Snapshot
url
string
relationship
Record
<string
, unknown
>
meta object describing the relationship
Returns
Promise
<AdapterPayload
>
promise
findMany()
findMany(
store,
type,
ids,
snapshots): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:656
Called by the store in order to fetch several records together if coalesceFindRequests
is true
For example, if the original payload looks like:
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
The IDs will be passed as a URL-encoded Array of IDs, in this form:
ids[]=1&ids[]=2&ids[]=3
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method.
The findMany
method makes an Ajax (HTTP GET) request to a URL computed by buildURL
, and returns a promise for the resulting payload.
Parameters
store
type
ids
string
[]
snapshots
Snapshot
<unknown
>[]
Returns
Promise
<AdapterPayload
>
promise
findRecord()
findRecord(
store,
type,
id,
snapshot): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:523
Called by the store in order to fetch the JSON for a given type and ID.
The findRecord
method makes an Ajax request to a URL computed by buildURL
, and returns a promise for the resulting payload.
This method performs an HTTP GET
request with the id provided as part of the query string.
Parameters
store
type
id
string
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Since
1.13.0
Overrides
get()
Call Signature
get<K>(key): RESTAdapter[K];
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:121
Retrieves the value of a property from the object.
This method is usually similar to using object[keyName]
or object.keyName
, however it supports both computed properties and the unknownProperty handler.
Because get
unifies the syntax for accessing all these kinds of properties, it can make many refactorings easier, such as replacing a simple property with a computed property, or vice versa.
Computed Properties
Computed properties are methods defined with the property
modifier declared at the end, such as:
import { computed } from '@ember/object';
fullName: computed('firstName', 'lastName', function() {
return this.get('firstName') + ' ' + this.get('lastName');
})
When you call get
on a computed property, the function will be called and the return value will be returned instead of the function itself.
Unknown Properties
Likewise, if you try to call get
on a property whose value is undefined
, the unknownProperty()
method will be called on the object. If this method returns any value other than undefined
, it will be returned instead. This allows you to implement "virtual" properties that are not defined upfront.
Type Parameters
K
K
extends keyof RESTAdapter
Parameters
key
K
Returns
RESTAdapter
[K
]
The property value or undefined.
Method
get
Inherited from
Call Signature
get(key): unknown;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:122
Parameters
key
string
Returns
unknown
Inherited from
getProperties()
Call Signature
getProperties<L>(list): { [Key in keyof default]: default[Key] };
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:144
To get the values of multiple properties at once, call getProperties
with a list of strings or an array:
record.getProperties('firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
is equivalent to:
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
Type Parameters
L
L
extends keyof RESTAdapter
[]
Parameters
list
L
of keys to get
Returns
{ [Key in keyof default]: default[Key] }
Method
getProperties
Inherited from
Call Signature
getProperties<L>(...list): { [Key in keyof default]: default[Key] };
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:149
Type Parameters
L
L
extends keyof RESTAdapter
[]
Parameters
list
...L
Returns
{ [Key in keyof default]: default[Key] }
Inherited from
Call Signature
getProperties<L>(list): { [Key in string]: unknown };
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:154
Type Parameters
L
L
extends string
[]
Parameters
list
L
Returns
{ [Key in string]: unknown }
Inherited from
Call Signature
getProperties<L>(...list): { [Key in string]: unknown };
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:159
Type Parameters
L
L
extends string
[]
Parameters
list
...L
Returns
{ [Key in string]: unknown }
Inherited from
groupRecordsForFindMany()
groupRecordsForFindMany(store, snapshots): Snapshot<unknown>[][];
Defined in: packages/adapter/src/rest.ts:884
Organize records into groups, each of which is to be passed to separate calls to findMany
.
This implementation groups together records that have the same base URL but differing ids. For example /comments/1
and /comments/2
will be grouped together because we know findMany can coalesce them together as /comments?ids[]=1&ids[]=2
It also supports urls where ids are passed as a query param, such as /comments?id=1
but not those where there is more than 1 query param such as /comments?id=2&name=David
Currently only the query param of id
is supported. If you need to support others, please override this or the _stripIDFromURL
method.
It does not group records that have differing base urls, such as for example: /posts/1/comments/2
and /posts/2/comments/3
Parameters
store
snapshots
Snapshot
<unknown
>[]
Returns
Snapshot
<unknown
>[][]
an array of arrays of records, each of which is to be loaded separately by findMany
.
Overrides
default
.groupRecordsForFindMany
handleResponse()
handleResponse(
status,
headers,
payload,
requestData): Payload | typeof _AdapterError;
Defined in: packages/adapter/src/rest.ts:937
Takes an ajax response, and returns the json payload or an error.
By default this hook just returns the json payload passed to it. You might want to override it in two cases:
Your API might return useful results in the response headers. Response headers are passed in as the second argument.
Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a
InvalidError
or aAdapterError
(or a sub class) from this hook and it will automatically reject the promise and put your record into the invalid or error state.
Returning a InvalidError
from this method will cause the record to transition into the invalid
state and make the errors
object available on the record. When returning an InvalidError
the store will attempt to normalize the error data returned from the server using the serializer's extractErrors
method.
Parameters
status
number
headers
Record
<string
, string
>
payload
Payload
requestData
the original request information
Returns
Payload
| typeof _AdapterError
response
Since
1.13.0
incrementProperty()
incrementProperty(keyName, increment?): number;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:372
Set the value of a property to the current value plus some amount.
person.incrementProperty('age');
team.incrementProperty('score', 2);
Parameters
keyName
keyof RESTAdapter
The name of the property to increment
increment?
number
The amount to increment by. Defaults to 1
Returns
number
The new property value
Method
incrementProperty
Inherited from
init()
init(_properties): void;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:114
An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition.
Example:
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
init() {
alert(`Name is ${this.get('name')}`);
}
});
let steve = Person.create({
name: 'Steve'
});
// alerts 'Name is Steve'.
NOTE: If you do override init
for a framework class like Component
from @ember/component
, be sure to call this._super(...arguments)
in your init
declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application.
Parameters
_properties
undefined
| object
Returns
void
Method
init
Inherited from
isInvalid()
isInvalid(
status,
_headers,
_payload): boolean;
Defined in: packages/adapter/src/rest.ts:996
Default handleResponse
implementation uses this hook to decide if the response is an invalid error.
Parameters
status
number
_headers
Record
<string
, unknown
>
_payload
Payload
Returns
boolean
Since
1.13.0
isSuccess()
isSuccess(
status,
_headers,
_payload): boolean;
Defined in: packages/adapter/src/rest.ts:981
Default handleResponse
implementation uses this hook to decide if the response is a success.
Parameters
status
number
_headers
Record
<string
, unknown
>
_payload
Payload
Returns
boolean
Since
1.13.0
notifyPropertyChange()
notifyPropertyChange(keyName): this;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:249
Convenience method to call propertyWillChange
and propertyDidChange
in succession.
Notify the observer system that a property has just changed.
Sometimes you need to change a value directly or indirectly without actually calling get()
or set()
on it. In this case, you can use this method instead. Calling this method will notify all observers that the property has potentially changed value.
Parameters
keyName
string
The property key to be notified about.
Returns
this
Method
notifyPropertyChange
Inherited from
pathForType()
pathForType(this, modelName): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:102
Parameters
this
MixtBuildURLMixin
modelName
string
Returns
string
query()
query(
store,
type,
query): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:579
Called by the store in order to fetch a JSON array for the records that match a particular query.
The query
method makes an Ajax (HTTP GET) request to a URL computed by buildURL
, and returns a promise for the resulting payload.
The query
argument is a simple JavaScript object that will be passed directly to the server as parameters.
Parameters
store
type
query
Record
<string
, unknown
>
Returns
Promise
<AdapterPayload
>
promise
Overrides
queryRecord()
queryRecord(
store,
type,
query,
adapterOptions): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:608
Called by the store in order to fetch a JSON object for the record that matches a particular query.
The queryRecord
method makes an Ajax (HTTP GET) request to a URL computed by buildURL
, and returns a promise for the resulting payload.
The query
argument is a simple JavaScript object that will be passed directly to the server as parameters.
Parameters
store
type
query
Record
<string
, unknown
>
adapterOptions
Record
<string
, unknown
>
Returns
Promise
<AdapterPayload
>
promise
Since
1.13.0
Overrides
removeObserver()
Call Signature
removeObserver<Target>(
key,
target,
method): this;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:352
Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to addObserver()
and your target will no longer receive notifications.
Type Parameters
Target
Target
Parameters
key
keyof RESTAdapter
The key to observe
target
Target
The target object to invoke
method
ObserverMethod
<Target
, RESTAdapter
>
The method to invoke
Returns
this
Method
removeObserver
Inherited from
Call Signature
removeObserver(key, method): this;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:357
Parameters
key
keyof RESTAdapter
method
ObserverMethod
<RESTAdapter
, RESTAdapter
>
Returns
this
Inherited from
reopen()
reopen(...args): this;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:81
Parameters
args
...(Record
<string
, unknown
> | Mixin
)[]
Returns
this
Inherited from
serialize()
serialize(snapshot, options): Record<string, unknown>;
Defined in: packages/adapter/src/index.ts:482
Proxies to the serializer's serialize
method.
Example
import Adapter from '@ember-data/adapter';
export default class ApplicationAdapter extends Adapter {
createRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let url = `/${type.modelName}`;
// ...
}
}
Parameters
snapshot
Snapshot
options
Returns
Record
<string
, unknown
>
serialized snapshot
Inherited from
set()
Call Signature
set<K, T>(key, value): T;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:208
Sets the provided key or path to the value.
record.set("key", value);
This method is generally very similar to calling object["key"] = value
or object.key = value
, except that it provides support for computed properties, the setUnknownProperty()
method and property observers.
Computed Properties
If you try to set a value on a key that has a computed property handler defined (see the get()
method for an example), then set()
will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties.
Unknown Properties
If you try to set a value on a key that is undefined in the target object, then the setUnknownProperty()
handler will be called instead. This gives you an opportunity to implement complex "virtual" properties that are not predefined on the object. If setUnknownProperty()
returns undefined, then set()
will simply set the value on the object.
Property Observers
In addition to changing the property, set()
will also register a property change with the object. Unless you have placed this call inside of a beginPropertyChanges()
and endPropertyChanges(),
any "local" observers (i.e. observer methods declared on the same object), will be called immediately. Any "remote" observers (i.e. observer methods declared on another object) will be placed in a queue and called at a later time in a coalesced manner.
Type Parameters
K
K
extends keyof RESTAdapter
T
T
extends | undefined
| null
| string
| number
| boolean
| string
[] | Record
<string
, unknown
> | (this
, id
, modelName
, snapshot
) => string
| (this
, modelName
, snapshots
) => string
| (this
, query
, modelName
) => string
| (this
, query
, modelName
) => string
| (this
, ids
, modelName
, snapshots
) => string
| (this
, id
, modelName
, snapshot
) => string
| (this
, id
, modelName
, snapshot
) => string
| (this
, modelName
, snapshot
) => string
| (this
, id
, modelName
, snapshot
) => string
| (this
, id
, modelName
, snapshot
) => string
| (this
, modelName
, id?
) => string
| (this
, path?
, parentURL?
) => string
| (this
, modelName
) => string
| { (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
, requestType
, query
): string
; (this
, modelName
, id
, snapshot
, requestType
, query
): string
; (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
, requestType
): string
; (this
, modelName
, id
, snapshot
): string
; } | FastBoot
| default
| unknown
[] | (store
, snapshot
) => boolean
| (store
, snapshotRecordArray
) => boolean
| (store
, snapshot
) => boolean
| (store
, snapshotRecordArray
) => boolean
| Owner
| (store
, type
, id
, snapshot
) => Promise
<AdapterPayload
> | (store
, type
, sinceToken
, snapshotRecordArray
) => Promise
<AdapterPayload
> | (store
, type
, query
) => Promise
<AdapterPayload
> | (store
, type
, query
, adapterOptions
) => Promise
<AdapterPayload
> | (store
, type
, snapshot
) => Promise
<AdapterPayload
> | (store
, schema
, snapshot
) => Promise
<AdapterPayload
> | (store
, schema
, snapshot
) => Promise
<AdapterPayload
> | (store
, snapshots
) => Snapshot
<unknown
>[][] | (...args
) => this
| (_properties
) => void
| () => this
| { <K
> (key
): RESTAdapter
[K
]; (key
): unknown
; } | { <L
> (list
): { [Key in keyof default]: default[Key] }
; <L
> (...list
): { [Key in keyof default]: default[Key] }
; <L
> (list
): { [Key in string]: unknown }
; <L
> (...list
): { [Key in string]: unknown }
; } | { <K
, T
> (key
, value
): T
; <T
> (key
, value
): T
; } | { <K
, P
> (hash
): P
; <T
> (hash
): T
; } | (keyName
) => this
| { <Target
> (key
, target
, method
): this
; (key
, method
): this
; } | { <Target
> (key
, target
, method
): this
; (key
, method
): this
; } | (keyName
, increment?
) => number
| (keyName
, decrement?
) => number
| (keyName
) => boolean
| <K
>(key
) => unknown
| () => string
| (obj
) => Record
<string
, unknown
> | (status
, _headers
, _payload
) => boolean
| (status
, _headers
, _payload
) => boolean
| { } | { } | (options
) => Promise
<Response
> | { } | (url
) => string
| (status
, headers
, payload
, requestData
) => Payload
| typeof _AdapterError
| { } | { } | (options
) => void
| (store
, snapshot
) => string
| (store
, type
, ids
, snapshots
) => Promise
<AdapterPayload
> | (snapshot
, options
) => Record
<string
, unknown
> | { } | () => void
| (store
, snapshot
, url
, relationship
) => Promise
<AdapterPayload
> | (store
, snapshot
, url
, relationship
) => Promise
<AdapterPayload
> | { } | (snapshot
) => QueryState
Parameters
key
K
value
T
The value to set or null
.
Returns
T
The passed value
Method
set
Inherited from
Call Signature
set<T>(key, value): T;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:209
Type Parameters
T
T
Parameters
key
string
value
T
Returns
T
Inherited from
setProperties()
Call Signature
setProperties<K, P>(hash): P;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:224
Sets a list of properties at once. These properties are set inside a single beginPropertyChanges
and endPropertyChanges
batch, so observers will be buffered.
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
Type Parameters
K
K
extends keyof RESTAdapter
P
P
extends { [Key in keyof default]: default[Key] }
Parameters
hash
P
the hash of keys and values to set
Returns
P
The passed in hash
Method
setProperties
Inherited from
Call Signature
setProperties<T>(hash): T;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:232
Type Parameters
T
T
extends Record
<string
, unknown
>
Parameters
hash
T
Returns
T
Inherited from
shouldBackgroundReloadAll()
shouldBackgroundReloadAll(store, snapshotRecordArray): boolean;
Defined in: packages/adapter/src/index.ts:893
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.
This method is only checked by the store when the store is returning a cached record array.
If this method returns true
the store will re-fetch all records from the adapter.
For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement shouldBackgroundReloadAll
as follows:
shouldBackgroundReloadAll(store, snapshotArray) {
let { downlink, effectiveType } = navigator.connection;
return downlink > 0 && effectiveType === '4g';
}
By default this method returns true
, indicating that a background reload should always be triggered.
Parameters
store
snapshotRecordArray
SnapshotRecordArray
Returns
boolean
Since
1.13.0
Inherited from
default
.shouldBackgroundReloadAll
shouldBackgroundReloadRecord()
shouldBackgroundReloadRecord(store, snapshot): boolean;
Defined in: packages/adapter/src/index.ts:857
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.
This method is only checked by the store when the store is returning a cached record.
If this method returns true
the store will re-fetch a record from the adapter.
For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement shouldBackgroundReloadRecord
as follows:
shouldBackgroundReloadRecord(store, snapshot) {
let { downlink, effectiveType } = navigator.connection;
return downlink > 0 && effectiveType === '4g';
}
By default, this hook returns true
so the data for the record is updated in the background.
Parameters
store
snapshot
Snapshot
Returns
boolean
Since
1.13.0
Inherited from
default
.shouldBackgroundReloadRecord
shouldReloadAll()
shouldReloadAll(store, snapshotRecordArray): boolean;
Defined in: packages/adapter/src/index.ts:821
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
.
If this method returns true
, the store will re-fetch all records from the adapter. If this method returns false
, the store will resolve immediately using the cached records.
For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write:
shouldReloadAll(store, snapshotArray) {
let snapshots = snapshotArray.snapshots();
return snapshots.any((ticketSnapshot) => {
let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt');
let timeDiff = moment().diff(lastAccessedAt, 'minutes');
if (timeDiff > 20) {
return true;
} else {
return false;
}
});
}
This method would ensure that whenever you do store.findAll('ticket')
you will always get a list of tickets that are no more than 20 minutes old. In case a cached version is more than 20 minutes old, findAll
will not resolve until you fetched the latest versions.
By default, this method returns true
if the passed snapshotRecordArray
is empty (meaning that there are no records locally available yet), otherwise, it returns false
.
Note that, with default settings, shouldBackgroundReloadAll
will always re-fetch all the records in the background even if shouldReloadAll
returns false
. You can override shouldBackgroundReloadAll
if this does not suit your use case.
Parameters
store
snapshotRecordArray
SnapshotRecordArray
Returns
boolean
Since
1.13.0
Inherited from
shouldReloadRecord()
shouldReloadRecord(store, snapshot): boolean;
Defined in: packages/adapter/src/index.ts:766
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
.
If this method returns true
, the store will re-fetch a record from the adapter. If this method returns false
, the store will resolve immediately using the cached record.
For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write:
shouldReloadRecord(store, ticketSnapshot) {
let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt');
let timeDiff = moment().diff(lastAccessedAt, 'minutes');
if (timeDiff > 20) {
return true;
} else {
return false;
}
}
This method would ensure that whenever you do store.findRecord('ticket', id)
you will always get a ticket that is no more than 20 minutes old. In case the cached version is more than 20 minutes old, findRecord
will not resolve until you fetched the latest version.
By default this hook returns false
, as most UIs should not block user interactions while waiting on data update.
Note that, with default settings, shouldBackgroundReloadRecord
will always re-fetch the records in the background even if shouldReloadRecord
returns false
. You can override shouldBackgroundReloadRecord
if this does not suit your use case.
Parameters
store
snapshot
Snapshot
Returns
boolean
Since
1.13.0
Inherited from
sortQueryParams()
sortQueryParams(obj): Record<string, unknown>;
Defined in: packages/adapter/src/rest.ts:368
By default, the RESTAdapter will send the query params sorted alphabetically to the server.
For example:
store.query('posts', { sort: 'price', category: 'pets' });
will generate a requests like this /posts?category=pets&sort=price
, even if the parameters were specified in a different order.
That way the generated URL will be deterministic and that simplifies caching mechanisms in the backend.
Setting sortQueryParams
to a falsey value will respect the original order.
In case you want to sort the query parameters with a different criteria, set sortQueryParams
to your custom sort function.
import RESTAdapter from '@ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
sortQueryParams(params) {
let sortedKeys = Object.keys(params).sort().reverse();
let len = sortedKeys.length, newParams = {};
for (let i = 0; i < len; i++) {
newParams[sortedKeys[i]] = params[sortedKeys[i]];
}
return newParams;
}
}
Parameters
obj
Record
<string
, unknown
>
Returns
Record
<string
, unknown
>
toggleProperty()
toggleProperty(keyName): boolean;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:401
Set the value of a boolean property to the opposite of its current value.
starship.toggleProperty('warpDriveEngaged');
Parameters
keyName
keyof RESTAdapter
The name of the property to toggle
Returns
boolean
The new property value
Method
toggleProperty
Inherited from
toString()
toString(): string;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:347
Returns a string representation which attempts to provide more information than Javascript's toString
typically does, in a generic way for all Ember objects.
import EmberObject from '@ember/object';
const Person = EmberObject.extend();
person = Person.create();
person.toString(); //=> "<Person:ember1024>"
If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass:
const Student = Person.extend();
let student = Student.create();
student.toString(); //=> "<(subclass of Person):ember1025>"
If the method toStringExtension
is defined, its return value will be included in the output.
const Teacher = Person.extend({
toStringExtension() {
return this.get('fullName');
}
});
teacher = Teacher.create();
teacher.toString(); //=> "<Teacher:ember1026:Tom Dale>"
Returns
string
string representation
Method
toString
Inherited from
updateRecord()
updateRecord(
store,
schema,
snapshot): Promise<AdapterPayload>;
Defined in: packages/adapter/src/rest.ts:803
Called by the store when an existing record is saved via the save
method on a model record instance.
The updateRecord
method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by buildURL
.
See serialize
for information on how to customize the serialized form of a record.
Parameters
store
schema
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Overrides
urlForCreateRecord()
urlForCreateRecord(
this,
modelName,
snapshot): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:98
Parameters
this
MixtBuildURLMixin
modelName
string
snapshot
Snapshot
Returns
string
urlForDeleteRecord()
urlForDeleteRecord(
this,
id,
modelName,
snapshot): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:100
Parameters
this
MixtBuildURLMixin
id
string
modelName
string
snapshot
Snapshot
Returns
string
urlForFindAll()
urlForFindAll(
this,
modelName,
snapshots): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:92
Parameters
this
MixtBuildURLMixin
modelName
string
snapshots
SnapshotRecordArray
Returns
string
urlForFindBelongsTo()
urlForFindBelongsTo(
this,
id,
modelName,
snapshot): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:97
Parameters
this
MixtBuildURLMixin
id
string
modelName
string
snapshot
Snapshot
Returns
string
urlForFindHasMany()
urlForFindHasMany(
this,
id,
modelName,
snapshot): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:96
Parameters
this
MixtBuildURLMixin
id
string
modelName
string
snapshot
Snapshot
Returns
string
urlForFindMany()
urlForFindMany(
this,
ids,
modelName,
snapshots): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:95
Parameters
this
MixtBuildURLMixin
ids
string
[]
modelName
string
snapshots
Snapshot
<unknown
>[]
Returns
string
urlForFindRecord()
urlForFindRecord(
this,
id,
modelName,
snapshot): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:91
Parameters
this
MixtBuildURLMixin
id
string
modelName
string
snapshot
Snapshot
Returns
string
urlForQuery()
urlForQuery(
this,
query,
modelName): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:94
Parameters
this
MixtBuildURLMixin
query
Record
<string
, unknown
>
modelName
string
Returns
string
urlForQueryRecord()
urlForQueryRecord(
this,
query,
modelName): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:93
Parameters
this
MixtBuildURLMixin
query
Record
<string
, unknown
>
modelName
string
Returns
string
urlForUpdateRecord()
urlForUpdateRecord(
this,
id,
modelName,
snapshot): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:99
Parameters
this
MixtBuildURLMixin
id
string
modelName
string
snapshot
Snapshot
Returns
string
urlPrefix()
urlPrefix(
this,
path?,
parentURL?): string;
Defined in: packages/adapter/src/-private/build-url-mixin.ts:101
Parameters
this
MixtBuildURLMixin
path?
null
| string
parentURL?
string
Returns
string
willDestroy()
willDestroy(): void;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:307
Override to implement teardown.
Returns
void
Method
willDestroy
Inherited from
create()
Call Signature
readonly static create<C>(this): InstanceType<C>;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:487
Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
helloWorld() {
alert(`Hi, my name is ${this.get('name')}`);
}
});
let tom = Person.create({
name: 'Tom Dale'
});
tom.helloWorld(); // alerts "Hi, my name is Tom Dale".
create
will call the init
function if defined during AnyObject.extend
If no arguments are passed to create
, it will not set values to the new instance during initialization:
let noName = Person.create();
noName.helloWorld(); // alerts undefined
NOTE: For performance reasons, you cannot declare methods or computed properties during create
. You should instead declare methods and computed properties when using extend
.
Type Parameters
C
C
extends typeof CoreObject
Parameters
this
C
Returns
InstanceType
<C
>
Method
create
For
@ember/object
Static
Inherited from
Call Signature
readonly static create<C, I, K, Args>(this, ...args): InstanceType<C> & MergeArray<Args>;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:488
Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
helloWorld() {
alert(`Hi, my name is ${this.get('name')}`);
}
});
let tom = Person.create({
name: 'Tom Dale'
});
tom.helloWorld(); // alerts "Hi, my name is Tom Dale".
create
will call the init
function if defined during AnyObject.extend
If no arguments are passed to create
, it will not set values to the new instance during initialization:
let noName = Person.create();
noName.helloWorld(); // alerts undefined
NOTE: For performance reasons, you cannot declare methods or computed properties during create
. You should instead declare methods and computed properties when using extend
.
Type Parameters
C
C
extends typeof CoreObject
I
I
extends CoreObject
K
K
extends string
| number
| symbol
Args
Args
extends Partial
<{ [Key in string | number | symbol]: I[Key] }>[]
Parameters
this
C
args
...Args
Returns
InstanceType
<C
> & MergeArray
<Args
>
Method
create
For
@ember/object
Static
Inherited from
detectInstance()
readonly static detectInstance(obj): boolean;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:600
Parameters
obj
unknown
Returns
boolean
Inherited from
extend()
readonly static extend<Statics, Instance, M>(this, ...mixins?): Readonly<Statics> & EmberClassConstructor<Instance> & MergeArray<M>;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:442
Creates a new subclass.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
alert(thing);
}
});
This defines a new subclass of EmberObject: Person
. It contains one method: say()
.
You can also create a subclass from any existing class by calling its extend()
method. For example, you might want to create a subclass of Ember's built-in Component
class:
import Component from '@ember/component';
const PersonComponent = Component.extend({
tagName: 'li',
classNameBindings: ['isAdministrator']
});
When defining a subclass, you can override methods but still access the implementation of your parent class by calling the special _super()
method:
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
let name = this.get('name');
alert(`${name} says: ${thing}`);
}
});
const Soldier = Person.extend({
say(thing) {
this._super(`${thing}, sir!`);
},
march(numberOfHours) {
alert(`${this.get('name')} marches for ${numberOfHours} hours.`);
}
});
let yehuda = Soldier.create({
name: 'Yehuda Katz'
});
yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!"
The create()
on line #17 creates an instance of the Soldier
class. The extend()
on line #8 creates a subclass of Person
. Any instance of the Person
class will not have the march()
method.
You can also pass Mixin
classes to add additional properties to the subclass.
import EmberObject from '@ember/object';
import Mixin from '@ember/object/mixin';
const Person = EmberObject.extend({
say(thing) {
alert(`${this.get('name')} says: ${thing}`);
}
});
const SingingMixin = Mixin.create({
sing(thing) {
alert(`${this.get('name')} sings: la la la ${thing}`);
}
});
const BroadwayStar = Person.extend(SingingMixin, {
dance() {
alert(`${this.get('name')} dances: tap tap tap tap `);
}
});
The BroadwayStar
class contains three methods: say()
, sing()
, and dance()
.
Type Parameters
Statics
Statics
Instance
Instance
M
M
extends unknown
[]
Parameters
this
Statics
& EmberClassConstructor
<Instance
>
mixins?
...M
One or more Mixin classes
Returns
Readonly
<Statics
> & EmberClassConstructor
<Instance
> & MergeArray
<M
>
Method
extend
Static
For
@ember/object
Inherited from
proto()
readonly static proto(): CoreObject;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:649
Returns
CoreObject
Inherited from
reopenClass()
readonly static reopenClass<C>(this, ...mixins): C;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:595
Augments a constructor's own properties and functions:
import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({
name: 'an object'
});
MyObject.reopenClass({
canBuild: false
});
MyObject.canBuild; // false
o = MyObject.create();
In other words, this creates static properties and functions for the class. These are only available on the class and not on any instance of that class.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
}
});
Person.reopenClass({
species: 'Homo sapiens',
createPerson(name) {
return Person.create({ name });
}
});
let tom = Person.create({
name: 'Tom Dale'
});
let yehuda = Person.createPerson('Yehuda Katz');
tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(Person.species); // "Homo sapiens"
Note that species
and createPerson
are not valid on the tom
and yehuda
variables. They are only valid on Person
.
To add functions and properties to instances of a constructor by extending the constructor's prototype see reopen
Type Parameters
C
C
extends typeof CoreObject
Parameters
this
C
mixins
...(Record
<string
, unknown
> | Mixin
)[]
Returns
C
Method
reopenClass
For
@ember/object
Static
Inherited from
toString()
static toString(): string;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:650
Returns
string
Inherited from
willReopen()
readonly static willReopen(): void;
Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:533
Returns
void