API Docs for: 0.25.0
Show:

OsfAdapter Class

Base adapter class for all OSF APIv2 endpoints

Methods

_addRelated

(
  • store
  • snapshot
  • addedSnapshots
  • relationship
  • url
  • isBulk
)
private

Handle add(s) of related resources. This differs from CREATEs in that the related record is already saved and is just being associated with the inverse record.

Parameters:

_ajaxRequest

(
  • options
)
private

Parameters:

  • options Object
    jQuery ajax options to be used for the ajax request

_buildRelationshipURL

(
  • snapshot
  • relationship
)
String private

Construct a URL for a relationship create/update/delete.

Parameters:

Returns:

String:

a URL

_buildURL

(
  • modelName
  • id
)
String private

Parameters:

Returns:

String: url

_createRelated

(
  • store
  • snapshot
  • createdSnapshots
  • relationship
  • url
  • isBulk
)
private

Handle creation of related resources

Parameters:

_deleteRelated

(
  • store
  • snapshot
  • deletedSnapshots
  • relationship
  • url
  • isBulk
)
private

Handle deletion of related resources

Parameters:

_doRelatedRequest

(
  • store
  • snapshot
  • relatedSnapshots
  • relationship
  • url
  • requestMethod
  • isBulk
)
private

A helper for making _*Related requests

Parameters:

_handleRelatedRequest

(
  • store
  • type
  • snapshot
  • relationship
  • change
)
private

Delegate a series of requests based on a snapshot, relationship, and a change. The change argument can be 'delete', 'remove', 'update', 'add', 'create'

Parameters:

_lazyInjections

() Object private
Returns a hash of property names and container names that injected properties will lookup on the container lazily.

Returns:

Object: Hash of all lazy injected property keys to container names

_makeRequest

(
  • request
)
Promise private
Make a request using jQuery.ajax.

Parameters:

Returns:

Promise: promise

_onLookup

() private
Provides lookup-time type validation for injected properties.

_removeRelated

(
  • store
  • snapshot
  • removedSnapshots
  • relationship
  • url
  • isBulk
)
private

Handle removal of related resources. This differs from DELETEs in that the related record is not deleted, just dissociated from the inverse record.

Parameters:

_requestFor

(
  • params
)
Object private
Get an object which contains all properties for a request which should be made.

Parameters:

Returns:

Object: request object

_requestToJQueryAjaxHash

(
  • request
)
Object private
Convert a request object into a hash which can be passed to jQuery.ajax.

Parameters:

Returns:

Object: jQuery ajax hash

_scheduledDestroy

() private
Invoked by the run loop to actually destroy the object. This is scheduled for execution by the destroy method.

_updateRelated

(
  • store
  • snapshot
  • updatedSnapshots
  • relationship
  • url
  • isBulk
)
private

Handle update(s) of related resources

Parameters:

addObserver

(
  • key
  • target
  • method
)
public
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. You can also pass an optional context parameter to this method. The context will be passed to your observer method whenever it is triggered. Note that if you add the same target/method pair on a key multiple times with different context parameters, your observer will only be called once with the last context you passed. ### Observer Methods Observer methods you pass should generally have the following signature if you do not pass a context parameter: `javascript fooDidChange: function(sender, key, value, rev) { }; ` 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. If you pass a context parameter, the context will be passed before the revision like so: `javascript fooDidChange: function(sender, key, value, context, rev) { }; ` Usually you will not need the value, context 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.

Parameters:

ajax

(
  • url
  • type
  • options
)
Promise private
Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into extractSingle or extractArray (depending on whether the original query was for one record or many records). By default, ajax method has the following behavior: * It sets the response dataType to "json" * If the HTTP method is not "GET", it sets the Content-Type to be application/json; charset=utf-8 * If the HTTP method is not "GET", it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers.

Parameters:

Returns:

Promise: promise

ajaxOptions

(
  • url
  • type
  • options
)
Object private

Inherited from DS.RESTAdapter but overwritten in addon/adapters/json-api.js:20

Parameters:

Returns:

beginPropertyChanges

() Ember.Observable private
Begins a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call this method at the beginning of the changes to begin deferring change notifications. When you are done making changes, call endPropertyChanges() to deliver the deferred change notifications and end deferring.

Returns:

buildQuery

()

Overrides buildQuery method - Allows users to embed resources with findRecord OSF APIv2 does not have "include" functionality, instead we use 'embed'. Usage: findRecord(type, id, {include: 'resource'}) or findRecord(type, id, {include: ['resource1', resource2]}) Swaps included resources with embedded resources

buildURL

(
  • modelName
  • id
  • snapshot
  • requestType
  • query
)
String
Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a /. When called by RESTAdapter.findMany() the id and snapshot parameters will be arrays of ids and snapshots.

Parameters:

  • modelName String
  • id (String | Array | Object)
    single id or array of ids or query
  • snapshot (DS.Snapshot | Array)
    single snapshot or array of snapshots
  • requestType String
  • query Object
    object of query parameters to send for query requests.

Returns:

String: url

cacheFor

(
  • keyName
)
Object public
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.

Parameters:

Returns:

Object: The cached value of the computed property, if any

createRecord

(
  • store
  • type
  • snapshot
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/rest.js:699

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:

Returns:

Promise: promise

dataForRequest

(
  • params
)
Object public
Get the data (body or query params) for a request.

Parameters:

Returns:

Object: data

decrementProperty

(
  • keyName
  • decrement
)
Number public
Set the value of a property to the current value minus some amount. `javascript player.decrementProperty('lives'); orc.decrementProperty('health', 5); `

Parameters:

  • keyName String
    The name of the property to decrement
  • decrement Number
    The amount to decrement by. Defaults to 1

Returns:

Number: The new property value

deleteRecord

(
  • store
  • type
  • snapshot
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/rest.js:771

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:

Returns:

Promise: promise

destroy

() Ember.Object public
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:

Ember.Object: receiver

endPropertyChanges

() Ember.Observable private
Ends a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call beginPropertyChanges() at the beginning of the changes to defer change notifications. When you are done making changes, call this method to deliver the deferred change notifications and end deferring.

Returns:

findAll

(
  • store
  • type
  • sinceToken
  • snapshotRecordArray
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/rest.js:438

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:

Returns:

Promise: promise

findBelongsTo

(
  • store
  • snapshot
  • url
)
Promise
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: `js { "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's host value prepended to it. * Links with no beginning / will have a parentURL prepended to it, via the current adapter's buildURL.

Parameters:

Returns:

Promise: promise

findHasMany

(
  • store
  • snapshot
  • url
)
Promise
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: `js { "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's host value prepended to it. * Links with no beginning / will have a parentURL prepended to it, via the current adapter's buildURL.

Parameters:

Returns:

Promise: promise

findMany

(
  • store
  • type
  • ids
  • snapshots
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/json-api.js:95

Parameters:

Returns:

Promise: promise

findRecord

(
  • store
  • type
  • id
  • snapshot
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/rest.js:405

Available since 1.13.0

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:

Returns:

Promise: promise

generatedDetailedMessage

(
  • status
  • headers
  • payload
  • requestData
)
String private
Generates a detailed ("friendly") error message, with plenty of information for debugging (good luck!)

Parameters:

Returns:

String: detailed error message

generateIdForRecord

(
  • store
  • type
  • inputProperties
)
(String | Number)
If the globally unique IDs for your records should be generated on the client, implement the generateIdForRecord() method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record'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: `javascript import DS from 'ember-data'; import { v4 } from 'uuid'; export default DS.Adapter.extend({ generateIdForRecord: function(store, inputProperties) { return v4(); } }); `

Parameters:

  • 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

get

(
  • keyName
)
Object public
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 fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', '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.

Parameters:

  • keyName String
    The property to retrieve

Returns:

Object: The property value or undefined.

getProperties

(
  • list
)
Object public
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' } `

Parameters:

  • list String... | Array
    of keys to get

Returns:

getWithDefault

(
  • keyName
  • defaultValue
)
Object public
Retrieves the value of a property, or a default value in the case that the property returns undefined. `javascript person.getWithDefault('lastName', 'Doe'); `

Parameters:

  • keyName String
    The name of the property to retrieve
  • defaultValue Object
    The value to return if the property value is undefined

Returns:

Object: The property value or the defaultValue.

groupRecordsForFindMany

(
  • store
  • snapshots
)
Array

Inherited from DS.Adapter but overwritten in addon/adapters/rest.js:821

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:

Returns:

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

handleResponse

(
  • status
  • headers
  • payload
  • requestData
)
Object | DS.AdapterError

Inherited from DS.RESTAdapter: addon/adapters/rest.js:885

Available since 1.13.0

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: 1. Your API might return useful results in the response headers. Response headers are passed in as the second argument. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a DS.InvalidError or a DS.AdapterError (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 DS.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 DS.InvalidError the store will attempt to normalize the error data returned from the server using the serializer's extractErrors method.

Parameters:

Returns:

Object | DS.AdapterError: response

hasObserverFor

(
  • key
)
Boolean private
Returns true if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object.

Parameters:

Returns:

headersForRequest

(
  • params
)
Object public
Get the headers for a request. By default the value of the headers property of the adapter is returned.

Parameters:

Returns:

Object: headers

incrementProperty

(
  • keyName
  • increment
)
Number public
Set the value of a property to the current value plus some amount. `javascript person.incrementProperty('age'); team.incrementProperty('score', 2); `

Parameters:

  • keyName String
    The name of the property to increment
  • increment Number
    The amount to increment by. Defaults to 1

Returns:

Number: The new property value

init

() public
An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition. Example: `javascript App.Person = Ember.Object.extend({ init: function() { alert('Name is ' + this.get('name')); } }); var steve = App.Person.create({ name: "Steve" }); // alerts 'Name is Steve'. ` NOTE: If you do override init for a framework class like Ember.View, 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.

isInvalid

(
  • status
  • headers
  • payload
)
Boolean

Inherited from DS.RESTAdapter: addon/adapters/rest.js:959

Available since 1.13.0

Default handleResponse implementation uses this hook to decide if the response is a an invalid error.

Parameters:

Returns:

isSuccess

(
  • status
  • headers
  • payload
)
Boolean

Inherited from DS.RESTAdapter: addon/adapters/rest.js:944

Available since 1.13.0

Default handleResponse implementation uses this hook to decide if the response is a success.

Parameters:

Returns:

methodForRequest

(
  • params
)
String public
Get the HTTP method for a request.

Parameters:

Returns:

String: HTTP method

normalizeErrorResponse

(
  • status
  • headers
  • payload
)
Array private

Parameters:

Returns:

Array: errors payload

notifyPropertyChange

(
  • keyName
)
Ember.Observable public
Convenience method to call propertyWillChange and propertyDidChange in succession.

Parameters:

  • keyName String
    The property key to be notified about.

Returns:

parseErrorResponse

(
  • responseText
)
Object private

Parameters:

Returns:

pathForType

(
  • modelName
)
String

Inherited from DS.BuildURLMixin but overwritten in addon/adapters/json-api.js:112

Parameters:

Returns:

String: path

propertyDidChange

(
  • keyName
)
Ember.Observable private
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 and propertyWillChange() instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call propertyWillChange and propertyDidChange as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like.

Parameters:

  • keyName String
    The property key that has just changed.

Returns:

propertyWillChange

(
  • keyName
)
Ember.Observable private
Notify the observer system that a property is about to change. 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 and propertyDidChange() instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call propertyWillChange and propertyDidChange as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like.

Parameters:

  • keyName String
    The property key that is about to change.

Returns:

query

(
  • store
  • type
  • query
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/rest.js:474

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:

Returns:

Promise: promise

queryRecord

(
  • store
  • type
  • query
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/rest.js:510

Available since 1.13.0

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:

Returns:

Promise: promise

removeObserver

(
  • key
  • target
  • method
)
public
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.

Parameters:

reopen

() public
Augments a constructor's prototype with additional properties and functions: `javascript MyObject = Ember.Object.extend({ name: 'an object' }); o = MyObject.create(); o.get('name'); // 'an object' MyObject.reopen({ say: function(msg){ console.log(msg); } }) o2 = MyObject.create(); o2.say("hello"); // logs "hello" o.say("goodbye"); // logs "goodbye" ` To add functions and properties to the constructor itself, see reopenClass

reopenClass

() public
Augments a constructor's own properties and functions: `javascript MyObject = Ember.Object.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 App.Person = Ember.Object.extend({ name : "", sayHello : function() { alert("Hello. My name is " + this.get('name')); } }); App.Person.reopenClass({ species : "Homo sapiens", createPerson: function(newPersonsName){ return App.Person.create({ name:newPersonsName }); } }); var tom = App.Person.create({ name : "Tom Dale" }); var yehuda = App.Person.createPerson("Yehuda Katz"); tom.sayHello(); // "Hello. My name is Tom Dale" yehuda.sayHello(); // "Hello. My name is Yehuda Katz" alert(App.Person.species); // "Homo sapiens" ` Note that species and createPerson are *not* valid on the tom and yehuda variables. They are only valid on App.Person. To add functions and properties to instances of a constructor by extending the constructor's prototype see reopen

serialize

(
  • snapshot
  • options
)
Object
Proxies to the serializer's serialize method. Example `app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = /${type.modelName}; // ... } }); `

Parameters:

Returns:

Object: serialized snapshot

set

(
  • keyName
  • value
)
Object public
Sets the provided key or path to the 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.

Parameters:

  • keyName String
    The property to set
  • value Object
    The value to set or null.

Returns:

Object: The passed value

setProperties

(
  • hash
)
Object public
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' }); `

Parameters:

  • hash Object
    the hash of keys and values to set

Returns:

Object: The passed in hash

shouldBackgroundReloadAll

(
  • store
  • snapshotRecordArray
)
Boolean

Inherited from DS.Adapter: addon/adapter.js:609

Available since 1.13.0

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: function(store, snapshotArray) { var 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.

Parameters:

Returns:

shouldBackgroundReloadRecord

(
  • store
  • snapshot
)
Boolean

Inherited from DS.Adapter: addon/adapter.js:570

Available since 1.13.0

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: function(store, snapshot) { var 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.

Parameters:

Returns:

shouldReloadAll

(
  • store
  • snapshotRecordArray
)
Boolean

Inherited from DS.Adapter: addon/adapter.js:522

Available since 1.13.0

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: function(store, snapshotArray) { var snapshots = snapshotArray.snapshots(); return snapshots.any(function(ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('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.

Parameters:

Returns:

shouldReloadRecord

(
  • store
  • snapshot
)
Boolean

Inherited from DS.Adapter: addon/adapter.js:479

Available since 1.13.0

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: function(store, ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('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.

Parameters:

Returns:

sortQueryParams

(
  • obj
)
Object
By default, the RESTAdapter will send the query params sorted alphabetically to the server. For example: `js 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. `app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ sortQueryParams: function(params) { var sortedKeys = Object.keys(params).sort().reverse(); var len = sortedKeys.length, newParams = {}; for (var i = 0; i < len; i++) { newParams[sortedKeys[i]] = params[sortedKeys[i]]; } return newParams; } }); `

Parameters:

Returns:

toggleProperty

(
  • keyName
)
Boolean public
Set the value of a boolean property to the opposite of its current value. `javascript starship.toggleProperty('warpDriveEngaged'); `

Parameters:

  • keyName String
    The name of the property to toggle

Returns:

Boolean: The new property value

toString

() String public
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 App.Person = Em.Object.extend() person = App.Person.create() person.toString() //=> "" ` If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass: `javascript Student = App.Person.extend() student = Student.create() student.toString() //=> "<(subclass of App.Person):ember1025>" ` If the method toStringExtension is defined, its return value will be included in the output. `javascript App.Teacher = App.Person.extend({ toStringExtension: function() { return this.get('fullName'); } }); teacher = App.Teacher.create() teacher.toString(); //=> "" `

Returns:

String: string representation

updateRecord

(
  • store
  • type
  • snapshot
)
Promise

Inherited from DS.Adapter but overwritten in addon/adapters/json-api.js:123

Parameters:

Returns:

Promise: promise

urlForCreateRecord

(
  • modelName
  • snapshot
)
String

Parameters:

Returns:

String: url

urlForDeleteRecord

(
  • id
  • modelName
  • snapshot
)
String

Parameters:

Returns:

String: url

urlForFindAll

(
  • modelName
  • snapshot
)
String

Parameters:

Returns:

String: url

urlForFindBelongsTo

(
  • id
  • modelName
  • snapshot
)
String

Parameters:

Returns:

String: url

urlForFindHasMany

(
  • id
  • modelName
  • snapshot
)
String

Parameters:

Returns:

String: url

urlForFindMany

(
  • ids
  • modelName
  • snapshots
)
String

Parameters:

Returns:

String: url

urlForFindRecord

(
  • id
  • modelName
  • snapshot
)
String

Parameters:

Returns:

String: url

urlForQuery

(
  • query
  • modelName
)
String

Parameters:

Returns:

String: url

urlForQueryRecord

(
  • query
  • modelName
)
String

Parameters:

Returns:

String: url

urlForRequest

(
  • params
)
String public
Get the URL for a request.

Parameters:

Returns:

String: URL

urlForUpdateRecord

(
  • id
  • modelName
  • snapshot
)
String

Parameters:

Returns:

String: url

urlPrefix

(
  • path
  • parentURL
)
String private

Parameters:

Returns:

String: urlPrefix

willDestroy

() public
Override to implement teardown.

Properties

coalesceFindRequests

Boolean

Inherited from DS.Adapter but overwritten in addon/adapters/json-api.js:46

By default the JSONAPIAdapter 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: `javascript { post: { id: 1, comments: [1, 2] } } ` By default calling post.get('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?filter[id]=1,2 ` Setting coalesceFindRequests to true also works for store.find requests and belongsTo relationships accessed within the same runloop. If you set coalesceFindRequests: true `javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ` will also send a request to: GET /comments?filter[id]=1,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.

concatenatedProperties

Array public
Defines the properties that will be concatenated from the superclass (instead of overridden). By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the classNames property of Ember.View. Here is some sample code showing the difference between a concatenated property and a normal one: `javascript App.BarView = Ember.View.extend({ someNonConcatenatedProperty: ['bar'], classNames: ['bar'] }); App.FooBarView = App.BarView.extend({ someNonConcatenatedProperty: ['foo'], classNames: ['foo'] }); var fooBarView = App.FooBarView.create(); fooBarView.get('someNonConcatenatedProperty'); // ['foo'] fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo'] ` This behavior extends to object creation as well. Continuing the above example: `javascript var view = App.FooBarView.create({ someNonConcatenatedProperty: ['baz'], classNames: ['baz'] }) view.get('someNonConcatenatedProperty'); // ['baz'] view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ` Adding a single property that is not an array will just add it in the array: `javascript var view = App.FooBarView.create({ classNames: 'baz' }) view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ` Using the concatenatedProperties property, we can tell Ember to mix the content of the properties. In Ember.View the classNameBindings and attributeBindings properties are also concatenated, in addition to classNames. This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual concatenated property (to not mislead your users to think they can override the property in a subclass).

Default: null

defaultSerializer

String
If you would like your adapter to use a custom serializer you can set the defaultSerializer property to be the name of the custom serializer. Note the defaultSerializer serializer has a lower priority than a model specific serializer (i.e. PostSerializer) or the application serializer. `app/adapters/django.js import DS from 'ember-data'; export default DS.Adapter.extend({ defaultSerializer: 'django' }); `

headers

Object
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](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). `app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); `

host

String
An adapter can target other hosts by setting the host property. `app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ` Requests for the Post model would now target https://api.example.com/post/.

isDestroyed

Unknown public
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

isDestroying

Unknown public
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

mergedProperties

Array public
Defines the properties that will be merged from the superclass (instead of overridden). By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by merging the superclass property value with the subclass property's value. An example of this in use within Ember is the queryParams property of routes. Here is some sample code showing the difference between a merged property and a normal one: `javascript App.BarRoute = Ember.Route.extend({ someNonMergedProperty: { nonMerged: 'superclass value of nonMerged' }, queryParams: { page: {replace: false}, limit: {replace: true} } }); App.FooBarRoute = App.BarRoute.extend({ someNonMergedProperty: { completelyNonMerged: 'subclass value of nonMerged' }, queryParams: { limit: {replace: false} } }); var fooBarRoute = App.FooBarRoute.create(); fooBarRoute.get('someNonMergedProperty'); // => { completelyNonMerged: 'subclass value of nonMerged' } // // Note the entire object, including the nonMerged property of // the superclass object, has been replaced fooBarRoute.get('queryParams'); // => { // page: {replace: false}, // limit: {replace: false} // } // // Note the page remains from the superclass, and the // limit property's value of false has been merged from // the subclass. ` This behavior is not available during object create calls. It is only available at extend time. This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual merged property (to not mislead your users to think they can override the property in a subclass).

Default: null

namespace

String
Endpoint paths can be prefixed with a namespace by setting the namespace property on the adapter: `app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ` Requests for the Post model would now target /api/1/post/.