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
- afterCreate
- afterCreateInstance
- afterDestroy
- afterEject
- afterFind
- afterFindAll
- afterInject
- afterLoadRelations
- afterReap
- afterUpdate
- afterValidate
- allowSimpleWhere
- basePath
- beforeCreate
- beforeCreateInstance
- beforeDestroy
- beforeEject
- beforeInject
- beforeReap
- beforeUpdate
- beforeValidate
- bypassCache
- cacheResponse
- clearEmptyQueries
- debug
- defaultAdapter
- defaultFilter
- defaultValues
- eagerEject
- endpoint
- error
- fallbackAdapters
- findAllFallbackAdapters
- findAllStrategy
- findFallbackAdapters
- findStrategy
- findStrictCache
- idAttribute
- ignoredChanges
- ignoreMissing
- instanceEvents
- keepChangeHistory
- linkRelations
- log
- maxAge
- notify
- omit
- onConflict
- reapAction
- reapInterval
- relationsEnumerable
- resetHistoryOnInject
- returnMeta
- scopes
- strategy
- upsert
- useClass
- useFilter
- validate
- watchChanges
actions
For quick definition of some static methods that hit your "action" endpoints. Only works if you have an HTTP adapter registered.
default | {} |
applies to | Resource 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.
type | function |
---|---|
default | js function afterCreate(resource, data, cb) { cb(null, data); } |
applies to | DS#create |
afterCreateInstance
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function afterCreateInstance(resource, data) { return data; } |
applies to | DS#createInstance |
afterDestroy
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function afterDestroy(Resource, data, cb) { cb(null, data); } |
applies to | DS#destroy , DS#destroyAll |
afterEject
Lifecycle hook. Synchronous.
type | function |
---|---|
default | js function afterEject(Resource, data) { return data; } |
applies to | DS#eject , DS#ejectAll |
afterFind
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function afterFind(Resource, data, cb) { cb(null, data); } |
applies to | DS#find |
afterFindAll
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function afterFindAll(Resource, data) { // Must return the data or a promise that resolves with the data return data; } |
applies to | DS#findAll |
afterInject
Lifecycle hook. Synchronous.
type | function |
---|---|
default | js function afterInject(resource, data) { return data; } |
applies to | DS#inject |
afterLoadRelations
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function afterLoadRelations(Resource, data, cb) { cb(null, data); } |
applies to | DS#loadRelations |
afterReap
Lifecycle hook. Synchronous.
type | function |
---|---|
default | js function afterReap(resource, data) { return data; } |
applies to | DS#reap |
afterUpdate
Lifecycle hook. Asynchronous. Called during .
type | function |
---|---|
default | js function afterUpdate(resource, data, cb) { cb(null, data); } |
applies to | DS#save , DS#update , DS#updateAll |
afterValidate
Lifecycle hook. Asynchronous.
type | function |
---|---|
js function afterValidate(resource, data, cb) { cb(null, data); } | |
applies to | DS#create , DS#save , DS#update , DS#updateAll |
allowSimpleWhere
Treat top-level fields on the params
argument as a simple "where" equality clauses.
type | boolean |
---|---|
default | true |
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"
type | string |
---|---|
default | "" |
beforeCreate
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function beforeCreate(resource, data, cb) { cb(null, data); } |
applies to | DS#create |
beforeCreateInstance
Lifecycle hook. Synchronous.
type | function |
---|---|
default | js function beforeCreateInstance(resource, data) { return data; } |
applies to | DS#createInstance |
beforeDestroy
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function beforeDestroy(resource, data, cb) { cb(null, data); } |
applies to | DS#destroy , DS#destroyAll |
beforeEject
Lifecycle hook. Synchronous.
type | function |
---|---|
default | js function beforeEject(resource, data) { return data; } |
applies to | DS#eject , DS#ejectAll |
beforeInject
Lifecycle hook. Synchronous.
type | function |
---|---|
default | js function beforeInject(resource, data) {} |
applies to | DS#find , DS#findAll , DS#create , DS#update , DS#updateAll |
beforeReap
Lifecycle hook. Synchronous.
type | function |
---|---|
default | js function beforeReap(resource, data) { return data; } |
applies to | DS#reap |
beforeUpdate
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function beforeUpdate(resource, data, cb) { cb(null, data); } |
applies to | DS#save , DS#update , DS#updateAll |
beforeValidate
Lifecycle hook. Asynchronous.
type | function |
---|---|
default | js function beforeValidate(resource, data, cb) { cb(null, data); } |
applies to | DS#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.
type | boolean |
---|---|
default | false |
applies to | DS#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.
type | boolean |
---|---|
default | Browser - true NodeJS - false |
applies to | DS#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.
type | boolean |
---|---|
default | true |
applies to | DS#eject , DS#ejectAll |
debug
Whether to print debugging logging statements when using js-data-debug.js.
type | boolean |
---|---|
default | false |
applies to | Everything |
defaultValues
Default values to apply to new Resource instances.
type | object |
---|---|
default | {} |
applies to | DS#createInstance |
defaultAdapter
The name of the registered adapter that should be used by default.
type | string |
---|---|
default | "http" |
applies to | DS#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])
type | function |
---|---|
default | JSData's default filter function |
applies to | DS#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.
type | boolean |
---|---|
default | false |
applies to | DS#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.
type | string |
---|---|
default | The value of Resource#name |
applies to | DS#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.
type | boolean or function |
---|---|
default | console.error |
applies to | errors |
fallbackAdapters
Specify adapters to be tried when using the "fallback"
strategy for DS#find
and DS#findAll
.
type | array |
---|---|
default | ["http"] |
applies to | DS#find , DS#findAll |
findAllFallbackAdapters
Specify adapters to be tried when using the "fallback"
strategy for DS#findAll
. If set, takes precedence over fallbackAdapters
.
type | array |
---|---|
default | null |
applies to | DS#findAll |
findAllStrategy
Adapter strategy to use for DS#findAll
. If set, takes precedence over `strategy.
type | string |
---|---|
default | null |
applies to | DS#findAll |
findFallbackAdapters
Specify adapters to be tried when using the "fallback"
strategy for DS#find
. If set, takes precedence over fallbackAdapters
.
type | array |
---|---|
default | null |
applies to | DS#find |
findStrategy
Adapter strategy to use for DS#find
. If set, takes precedence over `strategy.
type | string |
---|---|
default | null |
applies to | DS#find |
findStrictCache
Whether DS#find
should make an adapter request for an item that was injected manually, not injected via an adapter.
type | boolean |
---|---|
default | true |
applies to | DS#find |
idAttribute
The name of the field that specifies the primary key on data store items.
type | string |
---|---|
default | "id" |
applies to | everything |
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 "$"
.
type | array |
---|---|
default | [/\$/] |
applies to | dirty-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
type | boolean |
---|---|
default | Browser - true NodeJS - false |
applies to | instances |
keepChangeHistory
Whether to track changes (keep a history) of items in the data store.
default | false |
applies to | dirty-checking, DS#inject |
linkRelations
Whether to apply relation property accessors to all instances. See Relations.
type | boolean |
---|---|
default | Browser - true NodeJS - false |
applies to | instances |
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.
type | boolean or function |
---|---|
default | console.info or console.log |
applies to | debugging 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.
type | number (milliseconds) |
---|---|
default | null |
applies to | items 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.
type | boolean |
---|---|
default | Browser - true NodeJS - false |
applies to | DS#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.
type | array |
---|---|
default | [] , though it will be initialized to include the names of computed properties you define. |
applies to | DS#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.
type | string |
---|---|
default | "merge" |
possible values | - "merge" - Merge with the existing ditem- "replace" - Replace the existing item |
applies to | DS#inject |
reapAction
Action to take when reaping expired items from the data store. Has no effect if maxAge
is not set.
type | string |
---|---|
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 to | DS#reap |
reapInterval
How often to check for expired items. Has no effect if maxAge
is not set.
type | number (milliseconds) |
---|---|
default | 30000 (30 seconds) |
applies to | DS#reap |
relationsEnumerable
Whether relation property accessors should be enumerable. See Relations.
type | boolean |
---|---|
default | false |
applies to | instances |
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
.
type | boolean |
---|---|
default | true |
applies to | DS#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;
});
type | string |
---|---|
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 to | DS#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
.
type | object |
---|---|
default | js { 'defaultScope': { } } |
applies to | DS#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.
type | string |
---|---|
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 to | DS#find , DS#findAll |
upsert
If true
and the idAttribute
field is included in the object passed to DS#create
, call DS#update
instead.
type | boolean |
---|---|
default | Browser - true NodeJS - false |
applies to | DS#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
.
type | boolean or function |
---|---|
default | true |
applies to | items 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.
type | boolean |
---|---|
default | false |
applies to | DS#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.
default | js function validate(resource, data, cb) { cb(null, data); } |
applies to | DS#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.
default | Browser - true NodeJS - false |
applies to | DS#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.
Updated less than a minute ago