Class DS.Adapter

Extends: Ember.Object
Defined in: addon/adapter.js:7
Module: ember-data

createRecord (store, type, snapshot) Promise

Module: ember-data
store
DS.Store
type
DS.Model
the DS.Model class of the record
snapshot
DS.Snapshot
returns
Promise
promise

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
import DS from 'ember-data';
import { run } from '@ember/runloop';
import RSVP from 'RSVP';
import $ from 'jquery';

export default DS.Adapter.extend({
  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) {
        run(null, resolve, data);
      }, function(jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        run(null, reject, jqXHR);
      });
    });
  }
});

deleteRecord (store, type, snapshot) Promise

Module: ember-data
store
DS.Store
type
DS.Model
the DS.Model class of the record
snapshot
DS.Snapshot
returns
Promise
promise

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
import DS from 'ember-data';
import { run } from '@ember/runloop';
import RSVP from 'RSVP';
import $ from 'jquery';

export default DS.Adapter.extend({
  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) {
        run(null, resolve, data);
      }, function(jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        run(null, reject, jqXHR);
      });
    });
  }
});

findAll (store, type, sinceToken, snapshotRecordArray) Promise

Module: ember-data
store
DS.Store
type
DS.Model
sinceToken
String
snapshotRecordArray
DS.SnapshotRecordArray
returns
Promise
promise

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

Example

app/adapters/application.js
import DS from 'ember-data';
import RSVP from 'RSVP';
import $ from 'jquery';

export default DS.Adapter.extend({
  findAll(store, type, sinceToken) {
    let query = { since: sinceToken };

    return new RSVP.Promise(function(resolve, reject) {
      $.getJSON(`/${type.modelName}`, query).then(function(data) {
        resolve(data);
      }, function(jqXHR) {
        reject(jqXHR);
      });
    });
  }
});

findMany (store, type, ids, snapshots) Promise

Module: ember-data
store
DS.Store
type
DS.Model
the DS.Model class of the records
ids
Array
snapshots
Array
returns
Promise
promise

The store will call findMany instead of multiple findRecord requests to find multiple records at once if coalesceFindRequests is true.

app/adapters/application.js
import DS from 'ember-data';
import { run } from '@ember/runloop';
import RSVP from 'RSVP';
import $ from 'jquery';

export default DS.Adapter.extend({
  findMany(store, type, ids, snapshots) {
    return new RSVP.Promise(function(resolve, reject) {
      $.ajax({
        type: 'GET',
        url: `/${type.modelName}/`,
        dataType: 'json',
        data: { filter: { id: ids.join(',') } }
      }).then(function(data) {
        run(null, resolve, data);
      }, function(jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        run(null, reject, jqXHR);
      });
    });
  }
});

findRecord (store, type, id, snapshot) Promise

Module: ember-data
store
DS.Store
type
DS.Model
id
String
snapshot
DS.Snapshot
returns
Promise
promise

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 findRecord implementation:

app/adapters/application.js
import DS from 'ember-data';
import RSVP from 'RSVP';
import $ from 'jquery';

export default DS.Adapter.extend({
  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);
      });
    });
  }
});

generateIdForRecord (store, type, inputProperties) (String|Number)

Module: ember-data
store
DS.Store
type
DS.Model
the DS.Model class of the record
inputProperties
Object
a hash of properties to set on the newly created record.
returns
(String|Number)
id

If the globally unique IDs for your records should be generated on the client, implement the generateIdForRecord() method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's primaryKey.

Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls didCreateRecord(). Only implement this method if you intend to generate record IDs on the client-side.

The generateIdForRecord() method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter:

import DS from 'ember-data';
import { v4 } from 'uuid';

export default DS.Adapter.extend({
  generateIdForRecord(store, inputProperties) {
    return v4();
  }
});

groupRecordsForFindMany (store, snapshots) Array

Module: ember-data
store
DS.Store
snapshots
Array
returns
Array
an array of arrays of records, each of which is to be loaded separately by `findMany`.

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.

query (store, type, query, recordArray) Promise

Module: ember-data
store
DS.Store
type
DS.Model
query
Object
recordArray
DS.AdapterPopulatedRecordArray
returns
Promise
promise

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

Example

app/adapters/application.js
import DS from 'ember-data';
import RSVP from 'RSVP';
import $ from 'jquery';

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

queryRecord (store, type, query) Promise

Module: ember-data
store
DS.Store
type
subclass of DS.Model
query
Object
returns
Promise
promise

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
import DS from 'ember-data';
import RSVP from 'RSVP';
import $ from 'jquery';

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

serialize (snapshot, options) Object

Module: ember-data
snapshot
DS.Snapshot
options
Object
returns
Object
serialized snapshot

Proxies to the serializer's serialize method.

Example

app/adapters/application.js
import DS from 'ember-data';

export default DS.Adapter.extend({
  createRecord(store, type, snapshot) {
    let data = this.serialize(snapshot, { includeId: true });
    let url = `/${type.modelName}`;

    // ...
  }
});

shouldBackgroundReloadAll (store, snapshotRecordArray) Boolean

Module: ember-data

Available since v1.13.0

store
DS.Store
snapshotRecordArray
DS.SnapshotRecordArray
returns
Boolean

This method is used by the store to determine if the store should reload a record array after the store.findAll method resolves with a cached record array.

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 connection = window.navigator.connection;

  if (connection === 'cellular' || connection === 'none') {
    return false;
  } else {
    return true;
  }
}

By default this method returns true, indicating that a background reload should always be triggered.

shouldBackgroundReloadRecord (store, snapshot) Boolean

Module: ember-data

Available since v1.13.0

store
DS.Store
snapshot
DS.Snapshot
returns
Boolean

This method is used by the store to determine if the store should reload a record after the store.findRecord method resolves a cached record.

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 connection = window.navigator.connection;

  if (connection === 'cellular' || connection === 'none') {
    return false;
  } else {
    return true;
  }
}

By default this hook returns true so the data for the record is updated in the background.

shouldReloadAll (store, snapshotRecordArray) Boolean

Module: ember-data

Available since v1.13.0

store
DS.Store
snapshotRecordArray
DS.SnapshotRecordArray
returns
Boolean

This method is used by the store to determine if the store should reload all records from the adapter when records are requested by store.findAll.

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

shouldReloadRecord (store, snapshot) Boolean

Module: ember-data

Available since v1.13.0

store
DS.Store
snapshot
DS.Snapshot
returns
Boolean

This method is used by the store to determine if the store should reload a record from the adapter when a record is requested by store.findRecord.

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.

updateRecord (store, type, snapshot) Promise

Module: ember-data
store
DS.Store
type
DS.Model
the DS.Model class of the record
snapshot
DS.Snapshot
returns
Promise
promise

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
import DS from 'ember-data';
import { run } from '@ember/runloop';
import RSVP from 'RSVP';
import $ from 'jquery';

export default DS.Adapter.extend({
  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) {
        run(null, resolve, data);
      }, function(jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        run(null, reject, jqXHR);
      });
    });
  }
});

© 2020 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://api.emberjs.com/ember-data/2.18/classes/DS.Adapter/methods