Configuration

Defaults, and configuring data store settings

Settings can be set globally, per resource, and during a method call. Here are some quick examples:

var store = new JSData.DS({
  // set the default
  beforeCreate: function (resource, data, cb) {
    // do something general
    cb(null, data);
  }
});

var User = store.defineResource({
  name: 'user',
  // set just for this resource
  beforeCreate: function (resource, data, cb) {
    // do something more specific to "users"
    cb(null, data);
  }
});

User.create({ name: 'John', }, {
  // set just for this method call
  beforeCreate: function (resource, data, cb) {
    // do something specific for this method call
    cb(null, data);
  }
});

Table of Contents

actions

For quick definition of some static methods that hit your "action" endpoints. Only works if you have an HTTP adapter registered.

default{}
applies toResource definitions
Example
it('should allow definition of POST actions', function (done) {
    var _this = this;
    var newStore = new JSData.DS({
      debug: false,
      basePath: 'http://foo.com',
      actions: {
        test: {
          method: 'POST'
        }
      }
    });

    newStore.registerAdapter('http', dsHttpAdapter, { default: true });

    var Thing2 = newStore.defineResource({
      name: 'thing2',
      actions: {
        count: {
          method: 'POST'
        }
      }
    });


    Thing2.test({
      data: 'thing2 payload'
    }).then(function (data) {
      assert.equal(data.data, 'stuff');

      Thing2.count().then(function (data) {
        assert.equal(data.data, 'stuff2');

        done();
      });

      setTimeout(function () {
        try {
          assert.equal(2, _this.requests.length);
          assert.equal(_this.requests[1].url, 'http://foo.com/thing2/count');
          assert.equal(_this.requests[1].method, 'POST');
          _this.requests[1].respond(200, { 'Content-Type': 'text/plain' }, 'stuff2');
        } catch (err) {
          done(err);
        }
      }, 30);
    }).catch(done);

    setTimeout(function () {
      try {
        assert.equal(1, _this.requests.length);
        assert.equal(_this.requests[0].url, 'http://foo.com/thing2/test');
        assert.equal(_this.requests[0].method, 'POST');
        assert.equal(_this.requests[0].requestBody, 'thing2 payload');
        _this.requests[0].respond(200, { 'Content-Type': 'text/plain' }, 'stuff');
      } catch (err) {
        done(err);
      }
    }, 30);
  });

afterCreate

Lifecycle hook. Asynchronous.

typefunction
defaultjs function afterCreate(resource, data, cb) { cb(null, data); }
applies toDS#create

afterCreateInstance

Lifecycle hook. Asynchronous.

typefunction
defaultjs function afterCreateInstance(resource, data) { return data; }
applies toDS#createInstance

afterDestroy

Lifecycle hook. Asynchronous.

typefunction
defaultjs function afterDestroy(Resource, data, cb) { cb(null, data); }
applies toDS#destroy, DS#destroyAll

afterEject

Lifecycle hook. Synchronous.

typefunction
defaultjs function afterEject(Resource, data) { return data; }
applies toDS#eject, DS#ejectAll

afterFind

Lifecycle hook. Asynchronous.

typefunction
defaultjs function afterFind(Resource, data, cb) { cb(null, data); }
applies toDS#find

afterFindAll

Lifecycle hook. Asynchronous.

typefunction
defaultjs function afterFindAll(Resource, data) { // Must return the data or a promise that resolves with the data return data; }
applies toDS#findAll

afterInject

Lifecycle hook. Synchronous.

typefunction
defaultjs function afterInject(resource, data) { return data; }
applies toDS#inject

afterLoadRelations

Lifecycle hook. Asynchronous.

typefunction
defaultjs function afterLoadRelations(Resource, data, cb) { cb(null, data); }
applies toDS#loadRelations

afterReap

Lifecycle hook. Synchronous.

typefunction
defaultjs function afterReap(resource, data) { return data; }
applies toDS#reap

afterUpdate

Lifecycle hook. Asynchronous. Called during .

typefunction
defaultjs function afterUpdate(resource, data, cb) { cb(null, data); }
applies toDS#save, DS#update, DS#updateAll

afterValidate

Lifecycle hook. Asynchronous.

typefunction
js function afterValidate(resource, data, cb) { cb(null, data); }
applies toDS#create, DS#save, DS#update, DS#updateAll

allowSimpleWhere

Treat top-level fields on the params argument as a simple "where" equality clauses.

typeboolean
defaulttrue
Comment.filter({
  where: {
    userId: 10
  }
})

// same as above when "allowSimpleWhere" is true
Comment.filter({
  userId: 10
});

basePath

Base path to use when determining the path to a resource. Only really used by the http adapter. Example: "/api"

typestring
default""

beforeCreate

Lifecycle hook. Asynchronous.

typefunction
defaultjs function beforeCreate(resource, data, cb) { cb(null, data); }
applies toDS#create

beforeCreateInstance

Lifecycle hook. Synchronous.

typefunction
defaultjs function beforeCreateInstance(resource, data) { return data; }
applies toDS#createInstance

beforeDestroy

Lifecycle hook. Asynchronous.

typefunction
defaultjs function beforeDestroy(resource, data, cb) { cb(null, data); }
applies toDS#destroy, DS#destroyAll

beforeEject

Lifecycle hook. Synchronous.

typefunction
defaultjs function beforeEject(resource, data) { return data; }
applies toDS#eject, DS#ejectAll

beforeInject

Lifecycle hook. Synchronous.

typefunction
defaultjs function beforeInject(resource, data) {}
applies toDS#find, DS#findAll, DS#create, DS#update, DS#updateAll

beforeReap

Lifecycle hook. Synchronous.

typefunction
defaultjs function beforeReap(resource, data) { return data; }
applies toDS#reap

beforeUpdate

Lifecycle hook. Asynchronous.

typefunction
defaultjs function beforeUpdate(resource, data, cb) { cb(null, data); }
applies toDS#save, DS#update, DS#updateAll

beforeValidate

Lifecycle hook. Asynchronous.

typefunction
defaultjs function beforeValidate(resource, data, cb) { cb(null, data); }
applies toDS#create, DS#save, DS#update, DS#updateAll

bypassCache

Ignore any queries that have already been made or any data that is already in the data store and force the adapter to make the query.

typeboolean
defaultfalse
applies toDS#find, DS#findAll
// delegates to an adapter to get the user from a
// persistence layer so this will involve some 
// latency as it waits for the response
User.find(1).then(function (user) {
  // this will return immediately with the user
  // that is already in the data store
  return User.find(1);
}).then(function (user) {
  // unless you bypass the cache and force a new request
  return User.find(1, { bypassCache: true });
});

cacheResponse

Inject the data returned by adapters into the data store.

typeboolean
defaultBrowser - true
NodeJS - false
applies toDS#find, DS#findAll, DS#create, DS#save, DS#update, DS#updateAll
User.find(1).then(function (user) {
  // the user was injected into the data store
  user === User.get(1); // true
  
  // don't auto-inject this user into the store
  return User.find(2, { cacheResponse: false });
}).then(function (user) {
  User.get(2); // undefined
})

clearEmptyQueries

When ejecting items from the store, whether to check if they were in any cached queries, and if removing the item would make the query empty, and if so remove the cache query.

typeboolean
defaulttrue
applies toDS#eject, DS#ejectAll

debug

Whether to print debugging logging statements when using js-data-debug.js.

typeboolean
defaultfalse
applies toEverything

defaultValues

Default values to apply to new Resource instances.

typeobject
default{}
applies toDS#createInstance

defaultAdapter

The name of the registered adapter that should be used by default.

typestring
default"http"
applies toDS#find, DS#findAll, DS#create, DS#save, DS#update, DS#updateAll, DS#destroy, DS#destroyAll

defaultFilter

The default algorithm used by DS#filter. Supports the limit, skip or offset, sort or orderBy, and where keywords. You can find the source code for the algorithm here (look for the defaultFilter function).

You can provide your own filter function if your server has its own language for doing filtering, sorting, limiting, etc., and you want your frontend to speak the same language as your backend and filter/sort/etc. the same way too.

Signature: defaultFilter(collection, resourceName[, params][, options])

typefunction
defaultJSData's default filter function
applies toDS#filter

eagerEject

If true, eagerly eject the item from the store without waiting for the adapter's response, the item will be re-injected if the adapter operation fails.

typeboolean
defaultfalse
applies toDS#destroy, DS#destroyAll

endpoint

Specifies the endpoint for a resource. There isn't any sense setting a global endpoint, as endpoint will be different for every resource. By default, there isn't a global endpoint. When you define a resource you can specify an endpoint if it's different than the name of the resource.

typestring
defaultThe value of Resource#name
applies toDS#find, DS#findAll, DS#create, DS#save, DS#update, DS#updateAll, DS#destroy, DS#destroyAll

error

A function used to log errors. Default is console.error. Set to false to disable error logging, or set to your own function to capture the errors however you'd like.

typeboolean or function
defaultconsole.error
applies toerrors

fallbackAdapters

Specify adapters to be tried when using the "fallback" strategy for DS#find and DS#findAll.

typearray
default["http"]
applies toDS#find, DS#findAll

findAllFallbackAdapters

Specify adapters to be tried when using the "fallback" strategy for DS#findAll. If set, takes precedence over fallbackAdapters.

typearray
defaultnull
applies toDS#findAll

findAllStrategy

Adapter strategy to use for DS#findAll. If set, takes precedence over `strategy.

typestring
defaultnull
applies toDS#findAll

findFallbackAdapters

Specify adapters to be tried when using the "fallback" strategy for DS#find. If set, takes precedence over fallbackAdapters.

typearray
defaultnull
applies toDS#find

findStrategy

Adapter strategy to use for DS#find. If set, takes precedence over `strategy.

typestring
defaultnull
applies toDS#find

findStrictCache

Whether DS#find should make an adapter request for an item that was injected manually, not injected via an adapter.

typeboolean
defaulttrue
applies toDS#find

idAttribute

The name of the field that specifies the primary key on data store items.

typestring
default"id"
applies toeverything

ignoredChanges

Array of string and/or regular expressions used to match fields whose changes should be ignored. Defaults to ignoring changes to fields that start with "$".

typearray
default[/\$/]
applies todirty-checking

instanceEvents

If true instances will be capable of emitting events which you can listen to, similar to Backbone.Model instance events.

Events emitted by instances:

  • DS.change
typeboolean
defaultBrowser - true
NodeJS - false
applies toinstances

keepChangeHistory

Whether to track changes (keep a history) of items in the data store.

defaultfalse
applies todirty-checking, DS#inject

linkRelations

Whether to apply relation property accessors to all instances. See Relations.

typeboolean
defaultBrowser - true
NodeJS - false
applies toinstances

log

A function to log debugging messages. js-data.js and js-data.min.js have had the debugging messages stripped out, so you have to use js-data-debug.js for this option to have any effect. Set to false to disable the debug messages. Set to your own function to capture the messages however you'd like.

typeboolean or function
defaultconsole.info or console.log
applies todebugging messages in js-data-debug.js

maxAge

Whether to add an maximum age to items in the data store. According to reapInterval, the data store checks for items older than maxAge and initiates reapAction on them.

typenumber (milliseconds)
defaultnull
applies toitems in the data store

notify

Whether to activate the beforeEject, afterEject, beforeInject, afterInject, beforeCreateInstance, afterCreateInstance, beforeReap and afterReap lifecycle hooks and to emit the beforeEject, afterEject, beforeInject, afterInject, beforeReap and afterReap events.

typeboolean
defaultBrowser - true
NodeJS - false
applies toDS#eject, DS#ejectAll, DS#inject, DS#reap, DS#createInstance

omit

Array of strings or regular expressions that match the names of properties that should be omitted when sending data to an adapter. By default, the names of computed properties you defined will be included in this list.

typearray
default[], though it will be initialized to include the names of computed properties you define.
applies toDS#save, DS#update, DS#updateAll

onConflict

What to do when injecting an item into the store, when an item with the same primary key already exists in the store.

typestring
default"merge"
possible values- "merge" - Merge with the existing ditem
- "replace" - Replace the existing item
applies toDS#inject

reapAction

Action to take when reaping expired items from the data store. Has no effect if maxAge is not set.

typestring
default"inject" in the browser. "none" in NodeJS.
possible values- "none" - do nothing
- "inject" - reset the items' expiry timeout to the value of maxAge
- "eject" - eject the items from the store
- "refresh" - call DS#refresh on each item
applies toDS#reap

reapInterval

How often to check for expired items. Has no effect if maxAge is not set.

typenumber (milliseconds)
default30000 (30 seconds)
applies toDS#reap

relationsEnumerable

Whether relation property accessors should be enumerable. See Relations.

typeboolean
defaultfalse
applies toinstances

resetHistoryOnInject

Whether to reset an item's change history when the item is injected or re-injected into the store. Items (by default) are re-injected into the store after DS#find, DS#findAll, DS#save, DS#update, and DS#updateAll.

typeboolean
defaulttrue
applies toDS#inject

returnMeta

Whether the asynchronous methods (the ones that delegate to adapters), should return a value that includes both the normal response data and some meta data about the operation.

Examples
// Default (no meta)
User.find(1).then(function (user) { ... });
// returnMeta: "array"
User.find(1).spread(function (user, meta) { ... });
// returnMeta: "object"
User.find(1).then(function (data) {
  data.response;
  data.meta;
});
typestring
default"" (empty string)
possible values- "" (empty string) - return normal response
- "array" - return an array of the normal response and the meta data
- "object" - return an object that contains the properties response and meta
applies toDS#find, DS#findAll, DS#update, DS#save, DS#updateAll, DS#destroy, DS#destroyAll, DS#loadRelations, DS#create

scopes

Similar to Sequelize Scopes, scopes allow you to define commonly used queries that you can easily use later. You can apply one or more scopes to any method that takes a params argument. This includes DS#filter, DS#ejectAll, DS#findAll, DS#updateAll and DS#destroyAll.

typeobject
defaultjs { 'defaultScope': { } }
applies toDS#filter, DS#ejectAll, DS#findAll, DS#updateAll and DS#destroyAll
Example
var Post = store.defineResource({
  name: 'post',
  scopes: {
    // by default, filter for active posts
    defaultScope: {
      active: true
    },
    // for when we only want inactive posts
    inactive: {
      active: false
    }
  }
});

Post.inject([ {id: 1, active: true}, {id: 2, active: false} ]);
Post.filter(); // [ {id: 1, active: true} ]
Post.filter(null, {
  scope: 'inactive'
}); // [ {id: 2, active: false} ]

strategy

Adapter strategy to use for DS#find and DS#findAll. If set, findStrategy and findAllStrategy take precedence over `strategy.

typestring
default"single"
possible values- "single" - Use the defined default adapter
- "fallback" - Use the defined fallback adapters. If it fails with the first adapter, try the second, then the third, etc.
applies toDS#find, DS#findAll

upsert

If true and the idAttribute field is included in the object passed to DS#create, call DS#update instead.

typeboolean
defaultBrowser - true
NodeJS - false
applies toDS#create

useClass

Whether to wrap items of a Resource in the Resource's instance constructor. You can set this to your own constructor function, and the constructor function generated by JSData will inherit from your constructor function. Cannot be set to false.

typeboolean or function
defaulttrue
applies toitems in the data store
Example
function BaseUser() {}

var store = new JSData.DS();

Object.defineProperty(BaseUser.prototype, 'fullName', {
  get() {
    return this.firstName + ' ' + this.lastName;
  }
});

var User = store.defineResource({
  name: 'user',
  useClass: BaseUser
});

var user = User.createInstance({
  firstName: 'John',
  lastName: 'Anderson'
});

console.log(user.fullName); // "John Anderson"

useFilter

Whether DS#findAll should use DS#filter when returning cached data. If true then you can run into issues with pagination, e.g. you request page five but pages one through four are not in the data store yet, so DS#filter would return an empty array when requesting page five out of the cache. Therefore, this defaults to false. Meaning when a findAll query is cached and you make the query again you'll get back the same data that was returned the first time.

typeboolean
defaultfalse
applies toDS#findAll

validate

Lifecycle hook. Asynchronous. If using js-data-schema and you've defined a schema for a resource, the validate hook for that resource will be set to a function that uses the schema's validation function, instead of being a no-op.

defaultjs function validate(resource, data, cb) { cb(null, data); }
applies toDS#create, DS#save, DS#update, DS#updateAll

watchChanges

Whether change detection and the features that require it should be enabled. In the browser change detection is enabled by default. On the server it's disabled by default. Disabling change detection disables the standard computed properties, recording of change history, the automatic updating of entities' "last modified" timestamp, and the firing of the DS.change event.

defaultBrowser - true
NodeJS - false
applies toDS#lastModified, DS#changeHistory, computed properties, and the firing of the DS.change event.

📘

Need help?

Want more examples or have a question? Ask on the Gitter channel or post on the mailing list then we'll get your question answered and probably update this wiki.