Skip to content

Documentation / @warp-drive/legacy / adapter / Adapter

Defined in: warp-drive-packages/legacy/src/adapter.ts:257

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.

⚠️ CAUTION you likely want the docs for MinimumAdapterInterface as extending this abstract class is unnecessary.

Creating an Adapter

Create a new subclass of Adapter in the app/adapters folder:

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/adapter';

export default class extends Adapter {
  // ...your code here
}

Model-specific adapters can be created by putting your adapter class in an app/adapters/ + model-name + .js file of the application.

app/adapters/post.js
js
import { Adapter } from '@warp-drive/legacy/adapter';

export default class extends Adapter {
  // ...Post-specific adapter code goes here
}

Adapter 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:

  • findRecord()
  • createRecord()
  • updateRecord()
  • deleteRecord()
  • findAll()
  • query()

To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods:

  • findMany()

For an example of the implementation, see RESTAdapter, the included REST adapter.

Adapter

Extends

  • EmberObject

Extended by

Implements

Constructors

Constructor

ts
new Adapter(owner?): Adapter;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/index.d.ts:31

Parameters

owner?

Owner

Returns

Adapter

Inherited from

ts
EmberObject.constructor

Properties

_coalesceFindRequests

ts
_coalesceFindRequests: boolean;

Defined in: warp-drive-packages/legacy/src/adapter.ts:260


concatenatedProperties?

ts
optional concatenatedProperties: string | string[];

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:655

Inherited from

ts
EmberObject.concatenatedProperties

mergedProperties?

ts
optional mergedProperties: unknown[];

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:656

Inherited from

ts
EmberObject.mergedProperties

store

ts
store: default;

Defined in: warp-drive-packages/legacy/src/adapter.ts:258


_lazyInjections()?

ts
readonly static optional _lazyInjections: () => void;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:654

Returns

void

Inherited from

ts
EmberObject._lazyInjections

_onLookup()?

ts
readonly static optional _onLookup: (debugContainerKey) => void;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:653

Parameters

debugContainerKey

string

Returns

void

Inherited from

ts
EmberObject._onLookup

[INIT_FACTORY]?

ts
static optional [INIT_FACTORY]: null;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/mixin.d.ts:116

Inherited from

ts
EmberObject.[INIT_FACTORY]

isClass

ts
readonly static isClass: boolean;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:651

Inherited from

ts
EmberObject.isClass

isMethod

ts
readonly static isMethod: boolean;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:652

Inherited from

ts
EmberObject.isMethod

PrototypeMixin

ts
static PrototypeMixin: any;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:647

Inherited from

ts
EmberObject.PrototypeMixin

superclass

ts
static superclass: any;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:648

Inherited from

ts
EmberObject.superclass

Accessors

_debugContainerKey

Get Signature

ts
get _debugContainerKey(): false | `${string}:${string}`;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/index.d.ts:34

Returns

false | `${string}:${string}`

Inherited from

ts
EmberObject._debugContainerKey

coalesceFindRequests

Get Signature

ts
get coalesceFindRequests(): boolean;

Defined in: warp-drive-packages/legacy/src/adapter.ts:646

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.

Returns

boolean

Set Signature

ts
set coalesceFindRequests(value): void;

Defined in: warp-drive-packages/legacy/src/adapter.ts:654

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.

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.

Implementation of

MinimumAdapterInterface.coalesceFindRequests


isDestroyed

Get Signature

ts
get isDestroyed(): boolean;

Defined in: node_modules/.pnpm/[email protected]/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
ts
false
@public
Returns

boolean

Set Signature

ts
set isDestroyed(_value): void;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:273

Parameters
_value

boolean

Returns

void

Inherited from

ts
EmberObject.isDestroyed

isDestroying

Get Signature

ts
get isDestroying(): boolean;

Defined in: node_modules/.pnpm/[email protected]/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
ts
false
@public
Returns

boolean

Set Signature

ts
set isDestroying(_value): void;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:285

Parameters
_value

boolean

Returns

void

Inherited from

ts
EmberObject.isDestroying

Methods

addObserver()

Call Signature

ts
addObserver<Target>(
   key, 
   target, 
   method): this;

Defined in: node_modules/.pnpm/[email protected]/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).
app/components/my-component.js
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:

app/components/my-component.js
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 Adapter

The key to observe

target

Target

The target object to invoke

method

ObserverMethod<Target, Adapter>

The method to invoke

Returns

this

Method

addObserver

Inherited from
ts
EmberObject.addObserver

Call Signature

ts
addObserver(key, method): this;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:338

Parameters
key

keyof Adapter

method

ObserverMethod<Adapter, Adapter>

Returns

this

Inherited from
ts
EmberObject.addObserver

cacheFor()

ts
cacheFor<K>(key): unknown;

Defined in: node_modules/.pnpm/[email protected]/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 Adapter

Parameters

key

K

Returns

unknown

The cached value of the computed property, if any

Method

cacheFor

Inherited from

ts
EmberObject.cacheFor

createRecord()

ts
createRecord(
   store, 
   type, 
snapshot): Promise<AdapterPayload>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:526

Implement this method in a subclass to handle the creation of new records.

Serializes the record and sends it to the server.

Example

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';

export default class ApplicationAdapter extends Adapter {
  createRecord(store, type, snapshot) {
    let data = this.serialize(snapshot, { includeId: true });

    return new RSVP.Promise(function (resolve, reject) {
      $.ajax({
        type: 'POST',
        url: `/${type.modelName}`,
        dataType: 'json',
        data: data
      }).then(function (data) {
        resolve(data);
      }, function (jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        reject(jqXHR);
      });
    });
  }
}

Parameters

store

default

type

ModelSchema

the Model class of the record

snapshot

Snapshot

Returns

Promise<AdapterPayload>

promise

Implementation of

MinimumAdapterInterface.createRecord


decrementProperty()

ts
decrementProperty(keyName, decrement?): number;

Defined in: node_modules/.pnpm/[email protected]/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.

javascript
player.decrementProperty('lives');
orc.decrementProperty('health', 5);

Parameters

keyName

keyof Adapter

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

ts
EmberObject.decrementProperty

deleteRecord()

ts
deleteRecord(
   store, 
   type, 
snapshot): Promise<AdapterPayload>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:630

Implement this method in a subclass to handle the deletion of a record.

Sends a delete request for the record to the server.

Example

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';

export default class ApplicationAdapter extends Adapter {
  deleteRecord(store, type, snapshot) {
    let data = this.serialize(snapshot, { includeId: true });
    let id = snapshot.id;

    return new RSVP.Promise(function(resolve, reject) {
      $.ajax({
        type: 'DELETE',
        url: `/${type.modelName}/${id}`,
        dataType: 'json',
        data: data
      }).then(function(data) {
        resolve(data)
      }, function(jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        reject(jqXHR);
      });
    });
  }
}

Parameters

store

default

type

ModelSchema

the Model class of the record

snapshot

Snapshot

Returns

Promise<AdapterPayload>

promise

Implementation of

MinimumAdapterInterface.deleteRecord


destroy()

ts
destroy(): this;

Defined in: node_modules/.pnpm/[email protected]/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

Implementation of

MinimumAdapterInterface.destroy

Inherited from

ts
EmberObject.destroy

findAll()

ts
findAll(
   store, 
   type, 
   neverSet, 
snapshotRecordArray): Promise<AdapterPayload>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:333

The findAll() method is used to retrieve all records for a given type.

Example

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';

export default class ApplicationAdapter extends Adapter {
  findAll(store, type) {
    return new RSVP.Promise(function(resolve, reject) {
      $.getJSON(`/${type.modelName}`).then(function(data) {
        resolve(data);
      }, function(jqXHR) {
        reject(jqXHR);
      });
    });
  }
}

Parameters

store

default

type

ModelSchema

neverSet

null

a value is never provided to this argument

snapshotRecordArray

SnapshotRecordArray

Returns

Promise<AdapterPayload>

promise

Implementation of

MinimumAdapterInterface.findAll


findRecord()

ts
findRecord(
   store, 
   type, 
   id, 
snapshot): Promise<AdapterPayload>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:297

The findRecord() method is invoked when the store is asked for a record that has not previously been loaded. In response to findRecord() being called, you should query your persistence layer for a record with the given ID. The findRecord method should return a promise that will resolve to a JavaScript object that will be normalized by the serializer.

Here is an example of the findRecord implementation:

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';

export default class ApplicationAdapter extends Adapter {
  findRecord(store, type, id, snapshot) {
    return new RSVP.Promise(function(resolve, reject) {
      $.getJSON(`/${type.modelName}/${id}`).then(function(data) {
        resolve(data);
      }, function(jqXHR) {
        reject(jqXHR);
      });
    });
  }
}

Parameters

store

default

type

ModelSchema

id

string

snapshot

Snapshot

Returns

Promise<AdapterPayload>

promise

Implementation of

MinimumAdapterInterface.findRecord


get()

Call Signature

ts
get<K>(key): Adapter[K];

Defined in: node_modules/.pnpm/[email protected]/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:

javascript
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 Adapter

Parameters
key

K

Returns

Adapter[K]

The property value or undefined.

Method

get

Inherited from
ts
EmberObject.get

Call Signature

ts
get(key): unknown;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:122

Parameters
key

string

Returns

unknown

Inherited from
ts
EmberObject.get

getProperties()

Call Signature

ts
getProperties<L>(list): { [Key in keyof Adapter]: Adapter[Key] };

Defined in: node_modules/.pnpm/[email protected]/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:

javascript
record.getProperties('firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }

is equivalent to:

javascript
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
Type Parameters
L

L extends keyof Adapter[]

Parameters
list

L

of keys to get

Returns

{ [Key in keyof Adapter]: Adapter[Key] }

Method

getProperties

Inherited from
ts
EmberObject.getProperties

Call Signature

ts
getProperties<L>(...list): { [Key in keyof Adapter]: Adapter[Key] };

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:149

Type Parameters
L

L extends keyof Adapter[]

Parameters
list

...L

Returns

{ [Key in keyof Adapter]: Adapter[Key] }

Inherited from
ts
EmberObject.getProperties

Call Signature

ts
getProperties<L>(list): { [Key in string]: unknown };

Defined in: node_modules/.pnpm/[email protected]/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
ts
EmberObject.getProperties

Call Signature

ts
getProperties<L>(...list): { [Key in string]: unknown };

Defined in: node_modules/.pnpm/[email protected]/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
ts
EmberObject.getProperties

groupRecordsForFindMany()

ts
groupRecordsForFindMany(store, snapshots): Snapshot<unknown>[][];

Defined in: warp-drive-packages/legacy/src/adapter.ts:710

Organize records into groups, each of which is to be passed to separate calls to findMany.

For example, if your API has nested URLs that depend on the parent, you will want to group records by their parent.

The default implementation returns the records as a single group.

Parameters

store

default

snapshots

Snapshot<unknown>[]

Returns

Snapshot<unknown>[][]

an array of arrays of records, each of which is to be loaded separately by findMany.

Implementation of

MinimumAdapterInterface.groupRecordsForFindMany


incrementProperty()

ts
incrementProperty(keyName, increment?): number;

Defined in: node_modules/.pnpm/[email protected]/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.

javascript
person.incrementProperty('age');
team.incrementProperty('score', 2);

Parameters

keyName

keyof Adapter

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

ts
EmberObject.incrementProperty

init()

ts
init(_properties): void;

Defined in: node_modules/.pnpm/[email protected]/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:

javascript
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

ts
EmberObject.init

notifyPropertyChange()

ts
notifyPropertyChange(keyName): this;

Defined in: node_modules/.pnpm/[email protected]/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

ts
EmberObject.notifyPropertyChange

query()

ts
query(
   store, 
   type, 
query): Promise<AdapterPayload>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:377

This method is called when you call query on the store.

Example

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';

export default class ApplicationAdapter extends Adapter {
  query(store, type, query) {
    return new RSVP.Promise(function(resolve, reject) {
      $.getJSON(`/${type.modelName}`, query).then(function(data) {
        resolve(data);
      }, function(jqXHR) {
        reject(jqXHR);
      });
    });
  }
}

Parameters

store

default

type

ModelSchema

query

any

Returns

Promise<AdapterPayload>

promise

Implementation of

MinimumAdapterInterface.query


queryRecord()

ts
queryRecord(
   store, 
   type, 
   query, 
adapterOptions): Promise<AdapterPayload>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:414

The queryRecord() method is invoked when the store is asked for a single record through a query object.

In response to queryRecord() being called, you should always fetch fresh data. Once found, you can asynchronously call the store's push() method to push the record into the store.

Here is an example queryRecord implementation:

Example

app/adapters/application.js
js
import  { Adapter, BuildURLMixin } from '@warp-drive/legacy/adapter';

export default class ApplicationAdapter extends Adapter.extend(BuildURLMixin) {
  queryRecord(store, type, query) {
    return fetch(`/${type.modelName}`, { body: JSON.stringify(query) })
      .then((response) => response.json());
  }
}

Parameters

store

default

type

ModelSchema

query

any

adapterOptions

any

Returns

Promise<AdapterPayload>

promise

Implementation of

MinimumAdapterInterface.queryRecord


removeObserver()

Call Signature

ts
removeObserver<Target>(
   key, 
   target, 
   method): this;

Defined in: node_modules/.pnpm/[email protected]/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 Adapter

The key to observe

target

Target

The target object to invoke

method

ObserverMethod<Target, Adapter>

The method to invoke

Returns

this

Method

removeObserver

Inherited from
ts
EmberObject.removeObserver

Call Signature

ts
removeObserver(key, method): this;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:357

Parameters
key

keyof Adapter

method

ObserverMethod<Adapter, Adapter>

Returns

this

Inherited from
ts
EmberObject.removeObserver

reopen()

ts
reopen(...args): this;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:81

Parameters

args

...(Record<string, unknown> | Mixin)[]

Returns

this

Inherited from

ts
EmberObject.reopen

serialize()

ts
serialize(snapshot, options): Record<string, unknown>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:476

Proxies to the serializer's serialize method.

Example

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/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

SerializerOptions

Returns

Record<string, unknown>

serialized snapshot


set()

Call Signature

ts
set<K, T>(key, value): T;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:208

Sets the provided key or path to the value.

javascript
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 Adapter

T

T extends | undefined | string | boolean | unknown[] | default | string[] | Owner | (store, type, id, snapshot) => Promise<AdapterPayload> | (store, type, neverSet, snapshotRecordArray) => Promise<AdapterPayload> | (store, type, query) => Promise<AdapterPayload> | (store, type, query, adapterOptions) => Promise<AdapterPayload> | (store, type, snapshot) => Promise<AdapterPayload> | (store, type, snapshot) => Promise<AdapterPayload> | (store, type, snapshot) => Promise<AdapterPayload> | (store, snapshots) => Snapshot<unknown>[][] | (store, snapshot) => boolean | (store, snapshotRecordArray) => boolean | (store, snapshot) => boolean | (store, snapshotRecordArray) => boolean | () => string | { } | () => void | (...args) => this | (_properties) => void | () => this | { <K> (key): Adapter[K]; (key): unknown; } | { <L> (list): { [Key in keyof Adapter]: Adapter[Key] }; <L> (...list): { [Key in keyof Adapter]: Adapter[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 | (snapshot, options) => Record<string, unknown>

Parameters
key

K

value

T

The value to set or null.

Returns

T

The passed value

Method

set

Inherited from
ts
EmberObject.set

Call Signature

ts
set<T>(key, value): T;

Defined in: node_modules/.pnpm/[email protected]/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
ts
EmberObject.set

setProperties()

Call Signature

ts
setProperties<K, P>(hash): P;

Defined in: node_modules/.pnpm/[email protected]/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.

javascript
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
Type Parameters
K

K extends keyof Adapter

P

P extends { [Key in keyof Adapter]: Adapter[Key] }

Parameters
hash

P

the hash of keys and values to set

Returns

P

The passed in hash

Method

setProperties

Inherited from
ts
EmberObject.setProperties

Call Signature

ts
setProperties<T>(hash): T;

Defined in: node_modules/.pnpm/[email protected]/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
ts
EmberObject.setProperties

shouldBackgroundReloadAll()

ts
shouldBackgroundReloadAll(store, snapshotRecordArray): boolean;

Defined in: warp-drive-packages/legacy/src/adapter.ts:887

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:

javascript
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

default

snapshotRecordArray

SnapshotRecordArray

Returns

boolean

Since

1.13.0

Implementation of

MinimumAdapterInterface.shouldBackgroundReloadAll


shouldBackgroundReloadRecord()

ts
shouldBackgroundReloadRecord(store, snapshot): boolean;

Defined in: warp-drive-packages/legacy/src/adapter.ts:851

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:

javascript
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

default

snapshot

Snapshot

Returns

boolean

Since

1.13.0

Implementation of

MinimumAdapterInterface.shouldBackgroundReloadRecord


shouldReloadAll()

ts
shouldReloadAll(store, snapshotRecordArray): boolean;

Defined in: warp-drive-packages/legacy/src/adapter.ts:815

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:

javascript
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

default

snapshotRecordArray

SnapshotRecordArray

Returns

boolean

Since

1.13.0

Implementation of

MinimumAdapterInterface.shouldReloadAll


shouldReloadRecord()

ts
shouldReloadRecord(store, snapshot): boolean;

Defined in: warp-drive-packages/legacy/src/adapter.ts:760

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:

javascript
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

default

snapshot

Snapshot

Returns

boolean

Since

1.13.0

Implementation of

MinimumAdapterInterface.shouldReloadRecord


toggleProperty()

ts
toggleProperty(keyName): boolean;

Defined in: node_modules/.pnpm/[email protected]/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.

javascript
starship.toggleProperty('warpDriveEngaged');

Parameters

keyName

keyof Adapter

The name of the property to toggle

Returns

boolean

The new property value

Method

toggleProperty

Inherited from

ts
EmberObject.toggleProperty

toString()

ts
toString(): string;

Defined in: node_modules/.pnpm/[email protected]/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.

javascript
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:

javascript
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.

javascript
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

ts
EmberObject.toString

updateRecord()

ts
updateRecord(
   store, 
   type, 
snapshot): Promise<AdapterPayload>;

Defined in: warp-drive-packages/legacy/src/adapter.ts:582

Implement this method in a subclass to handle the updating of a record.

Serializes the record update and sends it to the server.

The updateRecord method is expected to return a promise that will resolve with the serialized record. This allows the backend to inform the Ember Data store the current state of this record after the update. If it is not possible to return a serialized record the updateRecord promise can also resolve with undefined and the Ember Data store will assume all of the updates were successfully applied on the backend.

Example

app/adapters/application.js
js
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';

export default class ApplicationAdapter extends Adapter {
  updateRecord(store, type, snapshot) {
    let data = this.serialize(snapshot, { includeId: true });
    let id = snapshot.id;

    return new RSVP.Promise(function(resolve, reject) {
      $.ajax({
        type: 'PUT',
        url: `/${type.modelName}/${id}`,
        dataType: 'json',
        data: data
      }).then(function(data) {
        resolve(data);
      }, function(jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        reject(jqXHR);
      });
    });
  }
}

Parameters

store

default

type

ModelSchema

the Model class of the record

snapshot

Snapshot

Returns

Promise<AdapterPayload>

promise

Implementation of

MinimumAdapterInterface.updateRecord


willDestroy()

ts
willDestroy(): void;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:307

Override to implement teardown.

Returns

void

Method

willDestroy

Inherited from

ts
EmberObject.willDestroy

create()

Call Signature

ts
readonly static create<C>(this): InstanceType<C>;

Defined in: node_modules/.pnpm/[email protected]/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.

javascript
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:

javascript
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
ts
EmberObject.create

Call Signature

ts
readonly static create<C, I, K, Args>(this, ...args): InstanceType<C> & MergeArray<Args>;

Defined in: node_modules/.pnpm/[email protected]/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.

javascript
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:

javascript
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
ts
EmberObject.create

detectInstance()

ts
readonly static detectInstance(obj): boolean;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:600

Parameters

obj

unknown

Returns

boolean

Inherited from

ts
EmberObject.detectInstance

extend()

ts
readonly static extend<Statics, Instance, M>(this, ...mixins?): Readonly<Statics> & EmberClassConstructor<Instance> & MergeArray<M>;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:442

Creates a new subclass.

javascript
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:

javascript
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:

javascript
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.

javascript
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

ts
EmberObject.extend

proto()

ts
readonly static proto(): CoreObject;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:649

Returns

CoreObject

Inherited from

ts
EmberObject.proto

reopenClass()

ts
readonly static reopenClass<C>(this, ...mixins): C;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:595

Augments a constructor's own properties and functions:

javascript
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.

javascript
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

ts
EmberObject.reopenClass

toString()

ts
static toString(): string;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:650

Returns

string

Inherited from

ts
EmberObject.toString

willReopen()

ts
readonly static willReopen(): void;

Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:533

Returns

void

Inherited from

ts
EmberObject.willReopen

Released under the MIT License.