new Mapper(opts)
The core of JSData's ORM/ODM implementation. Given a minimum amout of meta information about a resource, a Mapper can perform generic CRUD operations against that resource. Apart from its configuration, a Mapper is stateless. The particulars of various persistence layers have been abstracted into adapters, which a Mapper uses to perform its operations.
The term "Mapper" comes from the Data Mapper Pattern described in Martin Fowler's Patterns of Enterprise Application Architecture. A Data Mapper moves data between in-memory object instances and a relational or document-based database. JSData's Mapper can work with any persistence layer you can write an adapter for.
("Model" is a heavily overloaded term and is avoided in this documentation to prevent confusion.)
Name | Type | Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
opts |
Object | Configuration options. Properties
|
// Import and instantiate
import {Mapper} from 'js-data'
const UserMapper = new Mapper({ name: 'user' })
// Define a Mapper using the Container component
import {Container} from 'js-data'
const store = new Container()
store.defineMapper('user')
Extends
This class extends the Component class.Members
-
_adapters
-
Hash of registered adapters. Don't modify directly. Use Mapper#registerAdapter instead.
-
_listeners
-
Event listeners attached to this Component. Do not modify. Use Component#on and Component#off instead.
DetailsType Since Source Object 3.0.0 Component.js, line 52 - Inherited From:
-
applySchema
-
Whether to augment Mapper#recordClass with ES5 getters and setters according to the properties defined in Mapper#schema. This makes possible validation and change tracking on individual properties when using the dot (e.g.
user.name = "Bob"
) operator to modify a property, and istrue
by default. -
debug
-
Whether to enable debug-level logs for this component. Anything that extends
Component
inherits this option and the corresponding logging functionality.DetailsType Since Default value Source Boolean 3.0.0 false
Component.js, line 28 - Inherited From:
Example// Normally you would do: import {Component} from 'js-data' const JSData = require('js-data@3.0.0-beta.7') const {Component} = JSData console.log('Using JSData v' + JSData.version.full) const component = new Component() component.log('debug', 'some message') // nothing gets logged // Display debug logs: component.debug = true component.log('debug', 'other message') // this DOES get logged
-
defaultAdapter
-
The name of the registered adapter that this Mapper should used by default.
-
idAttribute
-
The field used as the unique identifier on records handled by this Mapper.
-
lifecycleMethods
-
The meta information describing this Mapper's available lifecycle methods. Do not modify.
-
methods
-
Functions that should be added to the prototype of Mapper#recordClass.
-
name
-
The name for this Mapper. This is the minimum amount of meta information required for a Mapper to be able to execute CRUD operations for a Resource.
-
notify
-
Whether this Mapper should emit operational events.
-
raw
-
Whether Mapper#create, Mapper#createMany, Mapper#update, Mapper#updateAll, Mapper#updateMany, Mapper#find, Mapper#findAll, Mapper#destroy, Mapper#destroyAll, Mapper#count, and Mapper#sum should return a raw result object that contains both the instance data returned by the adapter and metadata about the operation.
The default is to NOT return the result object, and instead return just the instance data.
-
recordClass
-
Set to
false
to force the Mapper to work with POJO objects only.Examples// Use POJOs only. import {Mapper, Record} from 'js-data' const UserMapper = new Mapper({ recordClass: false }) UserMapper.recordClass // false const user = UserMapper#createRecord() user instanceof Record // false
// Set to a custom class to have records wrapped in your custom class. import {Mapper, Record} from 'js-data' // Custom class class User { constructor (props = {}) { for (var key in props) { if (props.hasOwnProperty(key)) { this[key] = props[key] } } } } const UserMapper = new Mapper({ recordClass: User }) UserMapper.recordClass // function User() {} const user = UserMapper#createRecord() user instanceof Record // false user instanceof User // true
// Extend the Record class. import {Mapper, Record} from 'js-data' // Custom class class User extends Record { constructor () { super(props) } } const UserMapper = new Mapper({ recordClass: User }) UserMapper.recordClass // function User() {} const user = UserMapper#createRecord() user instanceof Record // true user instanceof User // true
-
schema
-
This Mapper's Schema.
Example// Normally you would do: import {Mapper} from 'js-data' const JSData = require('js-data@3.0.0-beta.7') const {Mapper} = JSData console.log('Using JSData v' + JSData.version.full) const UserMapper = new Mapper({ name: 'user', schema: { properties: { id: { type: 'number' }, first: { type: 'string', track: true }, last: { type: 'string', track: true }, role: { type: 'string', track: true, required: true }, age: { type: 'integer', track: true }, is_active: { type: 'number' } } } }) const user = UserMapper.createRecord({ id: 1, name: 'John', role: 'admin' }) user.on('change', function (user, changes) { console.log(changes) }) user.on('change:role', function (user, value) { console.log('change:role - ' + value) }) user.role = 'owner'
Methods
-
<static> extend(props, classProps)
-
Create a subclass of this Mapper:
Method parameters:Name Type Argument Default Description props
Object <optional>
{} Properties to add to the prototype of the subclass.
Properties
Name Type Argument Description constructor
Object <optional>
Provide a custom constructor function to be used as the subclass itself.
classProps
Object <optional>
{} Static properties to add to the subclass.
Return value:Type Description Constructor Subclass of this Mapper class.
Example// Normally you would do: import {Mapper} from 'js-data' const JSData = require('js-data@3.0.0-beta.7') const {Mapper} = JSData console.log('Using JSData v' + JSData.version.full) // Extend the class using ES2015 class syntax. class CustomMapperClass extends Mapper { foo () { return 'bar' } static beep () { return 'boop' } } const customMapper = new CustomMapperClass() console.log(customMapper.foo()) console.log(CustomMapperClass.beep()) // Extend the class using alternate method. const OtherMapperClass = Mapper.extend({ foo () { return 'bar' } }, { beep () { return 'boop' } }) const otherMapper = new OtherMapperClass() console.log(otherMapper.foo()) console.log(OtherMapperClass.beep()) // Extend the class, providing a custom constructor. function AnotherMapperClass () { Mapper.call(this) this.created_at = new Date().getTime() } Mapper.extend({ constructor: AnotherMapperClass, foo () { return 'bar' } }, { beep () { return 'boop' } }) const anotherMapper = new AnotherMapperClass() console.log(anotherMapper.created_at) console.log(anotherMapper.foo()) console.log(AnotherMapperClass.beep())
-
afterCount(query, opts, result)
-
Mapper lifecycle hook called by Mapper#count. If this method returns a promise then Mapper#count will wait for the promise to resolve before continuing.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#count.opts
Object The
opts
argument passed to Mapper#count.result
* The result, if any.
-
afterCreate(props, opts, result)
-
Mapper lifecycle hook called by Mapper#create. If this method returns a promise then Mapper#create will wait for the promise to resolve before continuing.
Method parameters:Name Type Description props
Object The
props
argument passed to Mapper#create.opts
Object The
opts
argument passed to Mapper#create.result
* The result, if any.
-
afterCreateMany(records, opts, result)
-
Mapper lifecycle hook called by Mapper#createMany. If this method returns a promise then Mapper#createMany will wait for the promise to resolve before continuing.
Method parameters:Name Type Description records
Array The
records
argument passed to Mapper#createMany.opts
Object The
opts
argument passed to Mapper#createMany.result
* The result, if any.
-
afterDestroy(id, opts, result)
-
Mapper lifecycle hook called by Mapper#destroy. If this method returns a promise then Mapper#destroy will wait for the promise to resolve before continuing.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#destroy.opts
Object The
opts
argument passed to Mapper#destroy.result
* The result, if any.
-
afterDestroyAll(data, query, opts, result)
-
Mapper lifecycle hook called by Mapper#destroyAll. If this method returns a promise then Mapper#destroyAll will wait for the promise to resolve before continuing.
Method parameters:Name Type Description data
* The
data
returned by the adapter.query
query The
query
argument passed to Mapper#destroyAll.opts
Object The
opts
argument passed to Mapper#destroyAll.result
* The result, if any.
-
afterFind(id, opts, result)
-
Mapper lifecycle hook called by Mapper#find. If this method returns a promise then Mapper#find will wait for the promise to resolve before continuing.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#find.opts
Object The
opts
argument passed to Mapper#find.result
* The result, if any.
-
afterFindAll(query, opts, result)
-
Mapper lifecycle hook called by Mapper#findAll. If this method returns a promise then Mapper#findAll will wait for the promise to resolve before continuing.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#findAll.opts
Object The
opts
argument passed to Mapper#findAll.result
* The result, if any.
-
afterSum(query, opts, result)
-
Mapper lifecycle hook called by Mapper#sum. If this method returns a promise then Mapper#sum will wait for the promise to resolve before continuing.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#sum.opts
Object The
opts
argument passed to Mapper#sum.result
* The result, if any.
-
afterUpdate(id, props, opts, result)
-
Mapper lifecycle hook called by Mapper#update. If this method returns a promise then Mapper#update will wait for the promise to resolve before continuing.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#update.props
props The
props
argument passed to Mapper#update.opts
Object The
opts
argument passed to Mapper#update.result
* The result, if any.
-
afterUpdateAll(props, query, opts, result)
-
Mapper lifecycle hook called by Mapper#updateAll. If this method returns a promise then Mapper#updateAll will wait for the promise to resolve before continuing.
Method parameters:Name Type Description props
Object The
props
argument passed to Mapper#updateAll.query
Object The
query
argument passed to Mapper#updateAll.opts
Object The
opts
argument passed to Mapper#updateAll.result
* The result, if any.
-
afterUpdateMany(records, opts, result)
-
Mapper lifecycle hook called by Mapper#updateMany. If this method returns a promise then Mapper#updateMany will wait for the promise to resolve before continuing.
Method parameters:Name Type Description records
Array The
records
argument passed to Mapper#updateMany.opts
Object The
opts
argument passed to Mapper#updateMany.result
* The result, if any.
-
beforeCount(query, opts)
-
Mapper lifecycle hook called by Mapper#count. If this method returns a promise then Mapper#count will wait for the promise to resolve before continuing.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#count.opts
Object The
opts
argument passed to Mapper#count. -
beforeCreate(props, opts)
-
Mapper lifecycle hook called by Mapper#create. If this method returns a promise then Mapper#create will wait for the promise to resolve before continuing.
Method parameters:Name Type Description props
Object The
props
argument passed to Mapper#create.opts
Object The
opts
argument passed to Mapper#create. -
beforeCreateMany(records, opts)
-
Mapper lifecycle hook called by Mapper#createMany. If this method returns a promise then Mapper#createMany will wait for the promise to resolve before continuing.
Method parameters:Name Type Description records
Array The
records
argument passed to Mapper#createMany.opts
Object The
opts
argument passed to Mapper#createMany. -
beforeDestroy(id, opts)
-
Mapper lifecycle hook called by Mapper#destroy. If this method returns a promise then Mapper#destroy will wait for the promise to resolve before continuing.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#destroy.opts
Object The
opts
argument passed to Mapper#destroy. -
beforeDestroyAll(query, opts)
-
Mapper lifecycle hook called by Mapper#destroyAll. If this method returns a promise then Mapper#destroyAll will wait for the promise to resolve before continuing.
Method parameters:Name Type Description query
query The
query
argument passed to Mapper#destroyAll.opts
Object The
opts
argument passed to Mapper#destroyAll. -
beforeFind(id, opts)
-
Mappers lifecycle hook called by Mapper#find. If this method returns a promise then Mapper#find will wait for the promise to resolve before continuing.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#find.opts
Object The
opts
argument passed to Mapper#find. -
beforeFindAll(query, opts)
-
Mapper lifecycle hook called by Mapper#findAll. If this method returns a promise then Mapper#findAll will wait for the promise to resolve before continuing.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#findAll.opts
Object The
opts
argument passed to Mapper#findAll. -
beforeSum(field, query, opts)
-
Mapper lifecycle hook called by Mapper#sum. If this method returns a promise then Mapper#sum will wait for the promise to resolve before continuing.
Method parameters:Name Type Description field
String The
field
argument passed to Mapper#sum.query
Object The
query
argument passed to Mapper#sum.opts
Object The
opts
argument passed to Mapper#sum. -
beforeUpdate(id, props, opts)
-
Mapper lifecycle hook called by Mapper#update. If this method returns a promise then Mapper#update will wait for the promise to resolve before continuing.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#update.props
props The
props
argument passed to Mapper#update.opts
Object The
opts
argument passed to Mapper#update. -
beforeUpdateAll(props, query, opts)
-
Mapper lifecycle hook called by Mapper#updateAll. If this method returns a promise then Mapper#updateAll will wait for the promise to resolve before continuing.
Method parameters:Name Type Description props
Object The
props
argument passed to Mapper#updateAll.query
Object The
query
argument passed to Mapper#updateAll.opts
Object The
opts
argument passed to Mapper#updateAll. -
beforeUpdateMany(records, opts)
-
Mapper lifecycle hook called by Mapper#updateMany. If this method returns a promise then Mapper#updateMany will wait for the promise to resolve before continuing.
Method parameters:Name Type Description records
Array The
records
argument passed to Mapper#updateMany.opts
Object The
opts
argument passed to Mapper#updateMany. -
belongsTo()
-
Define a belongsTo relationship. Only useful if you're managing your Mappers manually and not using a Container or DataStore component.
ExamplePostMapper.belongsTo(UserMapper, { // post.user_id points to user.id foreignKey: 'user_id' // user records will be attached to post records at "post.user" localField: 'user' }) CommentMapper.belongsTo(UserMapper, { // comment.user_id points to user.id foreignKey: 'user_id' // user records will be attached to comment records at "comment.user" localField: 'user' }) CommentMapper.belongsTo(PostMapper, { // comment.post_id points to post.id foreignKey: 'post_id' // post records will be attached to comment records at "comment.post" localField: 'post' })
-
count(query, opts)
-
Select records according to the
query
argument and return the count.Mapper#beforeCount will be called before calling the adapter. Mapper#afterCount will be called after calling the adapter.
Method parameters:Name Type Argument Default Description query
Object <optional>
{} Selection query. See query.
Properties
Name Type Argument Description where
Object <optional>
See query.where.
offset
Number <optional>
See query.offset.
limit
Number <optional>
See query.limit.
orderBy
String | Array.<Array> <optional>
See query.orderBy.
opts
Object <optional>
Configuration options. Refer to the
count
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
Return value:Type Description Promise Resolves with the count of the selected records.
Example// Get the number of published blog posts PostMapper.count({ status: 'published' }).then((numPublished) => { console.log(numPublished) // e.g. 45 })
-
create(props, opts)
-
Create and save a new the record using the provided
props
.Mapper#beforeCreate will be called before calling the adapter. Mapper#afterCreate will be called after calling the adapter.
Method parameters:Name Type Argument Description props
Object The properties for the new record.
opts
Object <optional>
Configuration options. Refer to the
create
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
with
Array.<String> <optional>
[] Relations to create in a cascading create if
props
contains nested relations. NOT performed in a transaction. Each nested create will result in another Mapper#create or Mapper#createMany call.pass
Array.<String> <optional>
[] Relations to send to the adapter as part of the payload. Normally relations are not sent.
Fires:
Return value:Type Description Promise Resolves with the created record.
Example// Create and save a new blog post PostMapper.create({ title: 'Modeling your data', status: 'draft' }).then((post) => { console.log(post) // { id: 1234, status: 'draft', ... } })
-
createInstance(props, opts)
-
Use Mapper#createRecord instead.
Method parameters:Name Type Argument Description props
Object | Array See Mapper#createRecord.
opts
Object <optional>
See Mapper#createRecord.
Return value:Type Description Object | Array See Mapper#createRecord.
- Deprecated:
-
- Yes
-
createMany(records, opts)
-
Given an array of records, batch create them via an adapter.
Mapper#beforeCreateMany will be called before calling the adapter. Mapper#afterCreateMany will be called after calling the adapter.
Method parameters:Name Type Argument Description records
Array.<Record> Array of records to be created in one batch.
opts
Object <optional>
Configuration options. Refer to the
createMany
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
with
Array.<String> <optional>
[] Relations to create in a cascading create if
records
contains nested relations. NOT performed in a transaction. Each nested create will result in another Mapper#createMany call.pass
Array.<String> <optional>
[] Relations to send to the adapter as part of the payload. Normally relations are not sent.
Fires:
Return value:Type Description Promise Resolves with the created records.
Example// Create and save several new blog posts PostMapper.createMany([{ title: 'Modeling your data', status: 'draft' }, { title: 'Reading data', status: 'draft' }]).then((posts) => { console.log(posts[0]) // { id: 1234, status: 'draft', ... } console.log(posts[1]) // { id: 1235, status: 'draft', ... } })
-
createRecord(props, opts)
-
Create an unsaved, uncached instance of this Mapper's Mapper#recordClass.
Returns
props
ifprops
is already an instance of Mapper#recordClass.Note: This method does not interact with any adapter, and does not save any data. It only creates new objects in memory.
Method parameters:Name Type Argument Description props
Object | Array.<Object> The properties for the Record instance or an array of property objects for the Record instances.
opts
Object <optional>
Configuration options.
Properties
Name Type Argument Default Description noValidate
Boolean <optional>
false Whether to skip validation when the Record instances are created.
Examples// Create empty unsaved record instance const post = PostMapper.createRecord()
// Create an unsaved record instance with inital properties const post = PostMapper.createRecord({ title: 'Modeling your data', status: 'draft' })
// Create a record instance that corresponds to a saved record const post = PostMapper.createRecord({ // JSData thinks this record has been saved if it has a primary key id: 1234, title: 'Modeling your data', status: 'draft' })
// Create record instances from an array const posts = PostMapper.createRecord([{ title: 'Modeling your data', status: 'draft' }, { title: 'Reading data', status: 'draft' }])
// Records are validated by default import {Mapper} from 'js-data' const PostMapper = new Mapper({ name: 'post', schema: { properties: { title: { type: 'string' } } } }) try { const post = PostMapper.createRecord({ title: 1234, }) } catch (err) { console.log(err.errors) // [{ expected: 'one of (string)', actual: 'number', path: 'title' }] }
// Skip validation import {Mapper} from 'js-data' const PostMapper = new Mapper({ name: 'post', schema: { properties: { title: { type: 'string' } } } }) const post = PostMapper.createRecord({ title: 1234, }, { noValidate: true }) console.log(post.isValid()) // false
-
crud(method, args)
-
Lifecycle invocation method. You probably won't call this method directly.
Method parameters:Name Type Argument Description method
String Name of the lifecycle method to invoke.
args
* <repeatable>
Arguments to pass to the lifecycle method.
Return value:Type Description Promise Unspecified -
dbg(args)
-
Log the provided values at the "debug" level. Debug-level logs are only logged if Component#debug is
true
..dbg(...)
is shorthand for.log('debug', ...)
.Method parameters:Name Type Argument Description args
* <optional>
<repeatable>
Values to log.
DetailsSince Source 3.0.0 Component.js, line 123 - Inherited From:
-
destroy(id, opts)
-
Using an adapter, destroy the record with the given primary key.
Mapper#beforeDestroy will be called before destroying the record. Mapper#afterDestroy will be called after destroying the record.
Method parameters:Name Type Argument Description id
String | Number The primary key of the record to destroy.
opts
Object <optional>
Configuration options. Refer to the
destroy
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
Fires:
Return value:Type Description Promise Resolves when the record has been destroyed. Resolves even if no record was found to be destroyed.
Examples// Destroy a specific blog post PostMapper.destroy(1234).then(() => { // Blog post #1234 has been destroyed })
// Get full response PostMapper.destroy(1234, { raw: true }).then((result) => { console.log(result.deleted) e.g. 1 console.log(...) // etc., more metadata can be found on the result })
-
destroyAll(query, opts)
-
Destroy the records selected by
query
via an adapter. If noquery
is provided then all records will be destroyed.Mapper#beforeDestroyAll will be called before destroying the records. Mapper#afterDestroyAll will be called after destroying the records.
Method parameters:Name Type Argument Default Description query
Object <optional>
{} Selection query. See query.
Properties
Name Type Argument Description where
Object <optional>
See query.where.
offset
Number <optional>
See query.offset.
limit
Number <optional>
See query.limit.
orderBy
String | Array.<Array> <optional>
See query.orderBy.
opts
Object <optional>
Configuration options. Refer to the
destroyAll
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
Fires:
Return value:Type Description Promise Resolves when the records have been destroyed. Resolves even if no records were found to be destroyed.
Examples// Destroy all blog posts PostMapper.destroyAll().then(() => { // All blog posts have been destroyed })
// Destroy all "draft" blog posts PostMapper.destroyAll({ status: 'draft' }).then(() => { // All "draft" blog posts have been destroyed })
// Get full response const query = null const options = { raw: true } PostMapper.destroyAll(query, options).then((result) => { console.log(result.deleted) e.g. 14 console.log(...) // etc., more metadata can be found on the result })
-
emit(event, args)
-
Trigger an event on this Component.
Method parameters:Name Type Argument Description event
String Name of event to emit.
args
* <optional>
<repeatable>
Arguments to pass to any listeners.
DetailsSince Source 3.0.0 Component.js, line 201 - Inherited From:
Example// import {Collection, DataStore} from 'js-data' const JSData = require('js-data@3.0.0-beta.7') const {Collection, DataStore} = JSData const collection = new Collection() collection.on('foo', (msg) => { console.log(msg) }) collection.emit('foo', 'bar') const store = new DataStore() store.on('beep', (msg) => { console.log(msg) }) store.emit('beep', 'boop')
-
find(id, opts)
-
Retrieve via an adapter the record with the given primary key.
Mapper#beforeFind will be called before calling the adapter. Mapper#afterFind will be called after calling the adapter.
Method parameters:Name Type Argument Description id
String | Number The primary key of the record to retrieve.
opts
Object <optional>
Configuration options. Refer to the
find
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
with
Array.<String> <optional>
[] Relations to eager load in the request.
Fires:
Return value:Type Description Promise Resolves with the found record. Resolves with
undefined
if no record was found.ExamplesPostMapper.find(1).then((post) => { console.log(post) // { id: 1, ...} })
// Get full response PostMapper.find(1, { raw: true }).then((result) => { console.log(result.data) // { id: 1, ...} console.log(result.found) // 1 console.log(...) // etc., more metadata can be found on the result })
-
findAll(query, opts)
-
Using the
query
argument, select records to retrieve via an adapter.Mapper#beforeFindAll will be called before calling the adapter. Mapper#afterFindAll will be called after calling the adapter.
Method parameters:Name Type Argument Default Description query
Object <optional>
{} Selection query. See query.
Properties
Name Type Argument Description where
Object <optional>
See query.where.
offset
Number <optional>
See query.offset.
limit
Number <optional>
See query.limit.
orderBy
String | Array.<Array> <optional>
See query.orderBy.
opts
Object <optional>
Configuration options. Refer to the
findAll
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
with
Array.<String> <optional>
[] Relations to eager load in the request.
Fires:
Return value:Type Description Promise Resolves with the found records, if any.
Examples// Find all "published" blog posts PostMapper.findAll({ status: 'published' }).then((posts) => { console.log(posts) // [{ id: 1, status: 'published', ...}, ...] })
// Get full response PostMapper.findAll({ status: 'published' }, { raw: true }).then((result) => { console.log(result.data) // [{ id: 1, status: 'published', ...}, ...] console.log(result.found) // e.g. 13 console.log(...) // etc., more metadata can be found on the result })
-
getAdapter(name)
-
Return the registered adapter with the given name or the default adapter if no name is provided.
Method parameters:Name Type Argument Description name
String <optional>
The name of the adapter to retrieve.
Return value:Type Description Adapter The adapter.
-
getAdapterName(opts)
-
Return the name of a registered adapter based on the given name or options, or the name of the default adapter if no name provided.
Method parameters:Name Type Argument Description opts
Object | String <optional>
The name of an adapter or options, if any.
Return value:Type Description String The name of the adapter.
-
getAdapters()
-
Get the object of registered adapters for this Mapper.
Return value:Type Description Object -
getSchema()
-
Returns this Mapper's Schema.
-
hasMany()
-
Defines a hasMany relationship. Only useful if you're managing your Mappers manually and not using a Container or DataStore component.
ExampleUserMapper.hasMany(PostMapper, { // post.user_id points to user.id foreignKey: 'user_id' // post records will be attached to user records at "user.posts" localField: 'posts' })
-
hasOne()
-
Defines a hasOne relationship. Only useful if you're managing your Mappers manually and not using a Container or DataStore component.
ExampleUserMapper.hasOne(ProfileMapper, { // profile.user_id points to user.id foreignKey: 'user_id' // profile records will be attached to user records at "user.profile" localField: 'profile' })
-
is(record)
-
Return whether
record
is an instance of this Mapper's recordClass.Return value:Type Description Boolean Whether
record
is an instance of this Mapper's Mapper#recordClass.Exampleconst post = PostMapper.createRecord() console.log(PostMapper.is(post)) // true // Equivalent to what's above console.log(post instanceof PostMapper.recordClass) // true
-
log(level, args)
-
Log the provided values. By default sends values to
console[level]
. Debug-level logs are only logged if Component#debug istrue
.Will attempt to use appropriate
console
methods if they are available.Method parameters:Name Type Argument Description level
String Log level.
args
* <optional>
<repeatable>
Values to log.
DetailsSince Source 3.0.0 Component.js, line 133 - Inherited From:
-
off(event, listener)
-
Remove an event listener from this Component. If no listener is provided, then all listeners for the specified event will be removed. If no event is specified then all listeners for all events will be removed.
Method parameters:Name Type Argument Description event
String <optional>
Name of event to unsubsribe to.
listener
Function <optional>
Listener to remove.
DetailsSince Source 3.0.0 Component.js, line 179 - Inherited From:
Examples// Remove a particular listener for a particular event collection.off('add', handler)
// Remove all listeners for a particular event record.off('change')
// Remove all listeners to all events store.off()
-
on(event, listener, ctx)
-
Register a new event listener on this Component.
Method parameters:Name Type Argument Description event
String Name of event to subsribe to.
listener
Function Listener function to handle the event.
ctx
* <optional>
Optional content in which to invoke the listener.
DetailsSince Source 3.0.0 Component.js, line 146 - Inherited From:
Examples// Listen for all "afterCreate" events in a DataStore store.on('afterCreate', (mapperName, props, opts, result) => { console.log(mapperName) // "post" console.log(props.id) // undefined console.log(result.id) // 1234 }) store.create('post', { title: 'Modeling your data' }).then((post) => { console.log(post.id) // 1234 })
// Listen for the "add" event on a collection collection.on('add', (records) => { console.log(records) // [...] })
// Listen for "change" events on a record post.on('change', (record, changes) => { console.log(changes) // { changed: { title: 'Modeling your data' } } }) post.title = 'Modeling your data'
-
registerAdapter(name, adapter, opts)
-
Register an adapter on this Mapper under the given name.
Method parameters:Name Type Argument Description name
String The name of the adapter to register.
adapter
Adapter The adapter to register.
opts
Object <optional>
Configuration options.
Properties
Name Type Argument Default Description default
Boolean <optional>
false Whether to make the adapter the default adapter for this Mapper.
-
sum(field, query, opts)
-
Select records according to the
query
argument, and aggregate the sum value of the property specified byfield
.Mapper#beforeSum will be called before calling the adapter. Mapper#afterSum will be called after calling the adapter.
Method parameters:Name Type Argument Default Description field
String The field to sum.
query
Object <optional>
{} Selection query. See query.
Properties
Name Type Argument Description where
Object <optional>
See query.where.
offset
Number <optional>
See query.offset.
limit
Number <optional>
See query.limit.
orderBy
String | Array.<Array> <optional>
See query.orderBy.
opts
Object <optional>
Configuration options. Refer to the
sum
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
Return value:Type Description Promise Resolves with the aggregated sum.
ExamplePurchaseOrderMapper.sum('amount', { status: 'paid' }).then((amountPaid) => { console.log(amountPaid) // e.g. 451125.34 })
-
toJSON(records, opts)
-
Return a plain object representation of the given record. Relations can be optionally be included. Non-schema properties can be excluded.
Method parameters:Name Type Argument Description records
Record | Array.<Record> Record or records from which to create a POJO representation.
opts
Object <optional>
Configuration options.
Properties
Name Type Argument Description strict
Boolean <optional>
Whether to exclude properties that are not defined in Mapper#schema.
with
Array.<String> <optional>
Array of relation names or relation fields to include in the POJO representation.
withAll
Boolean <optional>
Whether to simply include all relations in the representation. Overrides
opts.with
.Return value:Type Description Object | Array.<Object> POJO representation of the record or records.
Exampleimport {Mapper, Schema} from 'js-data' const PersonMapper = new Mapper({ name: 'person', schema: { properties: { name: { type: 'string' }, id: { type: 'string' } } } }) const person = PersonMapper.createRecord({ id: 1, name: 'John', foo: 'bar' }) console.log(PersonMapper.toJSON(person)) // {"id":1,"name":"John","foo":"bar"} console.log(PersonMapper.toJSON(person), { strict: true }) // {"id":1,"name":"John"}
-
update(id, props, opts)
-
Using an adapter, update the record with the primary key specified by the
id
argument.Mapper#beforeUpdate will be called before updating the record. Mapper#afterUpdate will be called after updating the record.
Method parameters:Name Type Argument Description id
String | Number The primary key of the record to update.
props
Object The update to apply to the record.
opts
Object <optional>
Configuration options. Refer to the
update
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw. transaction.
Fires:
Return value:Type Description Promise Resolves with the updated record. Rejects if the record could not be found.
Example// Update a specific post PostMapper.update(1234, { status: 'published', published_at: new Date() }).then((post) => { console.log(post) // { id: 1234, status: 'published', ... } })
-
updateAll(props, query, opts)
-
Using the
query
argument, perform the a single updated to the selected records.Mapper#beforeUpdateAll will be called before making the update. Mapper#afterUpdateAll will be called after making the update.
Method parameters:Name Type Argument Default Description props
Object Update to apply to selected records.
query
Object <optional>
{} Selection query. See query.
Properties
Name Type Argument Description where
Object <optional>
See query.where.
offset
Number <optional>
See query.offset.
limit
Number <optional>
See query.limit.
orderBy
String | Array.<Array> <optional>
See query.orderBy.
opts
Object <optional>
Configuration options. Refer to the
updateAll
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
Fires:
Return value:Type Description Promise Resolves with the update records, if any.
Example// Turn all of John's blog posts into drafts. const update = { status: draft: published_at: null } const query = { userId: 1234 } PostMapper.updateAll(update, query).then((posts) => { console.log(posts) // [...] })
-
updateMany(records, opts)
-
Given an array of updates, perform each of the updates via an adapter. Each "update" is a hash of properties with which to update an record. Each update must contain the primary key of the record to be updated.
Mapper#beforeUpdateMany will be called before making the update. Mapper#afterUpdateMany will be called after making the update.
Method parameters:Name Type Argument Description records
Array.<Record> Array up record updates.
opts
Object <optional>
Configuration options. Refer to the
updateMany
method of whatever adapter you're using for more configuration options.Properties
Name Type Argument Default Description adapter
Boolean <optional>
Mapper#defaultAdapter Name of the adapter to use.
notify
Boolean <optional>
Mapper#notify See Mapper#notify.
raw
Boolean <optional>
Mapper#raw See Mapper#raw.
Fires:
Return value:Type Description Promise Resolves with the updated records. Rejects if any of the records could be found.
ExamplePostMapper.updateMany([ { id: 1234, status: 'draft' }, { id: 2468, status: 'published', published_at: new Date() } ]).then((posts) => { console.log(posts) // [...] })
-
validate(record, opts)
-
Validate the given record or records according to this Mapper's Schema. If there are no validation errors then the return value will be
undefined
.Method parameters:Name Type Argument Description record
Object | Array.<Object> The record or records to validate.
opts
Object <optional>
Configuration options. Passed to Schema#validate.
Exampleimport {Mapper, Schema} from 'js-data' const PersonSchema = new Schema({ properties: { name: { type: 'string' }, id: { type: 'string' } } }) const PersonMapper = new Mapper({ name: 'person', schema: PersonSchema }) let errors = PersonMapper.validate({ name: 'John' }) console.log(errors) // undefined errors = PersonMapper.validate({ name: 123 }) console.log(errors) // [{ expected: 'one of (string)', actual: 'number', path: 'name' }]
-
wrap(data, opts)
-
Method used to wrap data returned by an adapter with this Mapper's Mapper#recordClass. This method is used by all of a Mapper's CRUD methods. The provided implementation of this method assumes that the
data
passed to it is a record or records that need to be wrapped with Mapper#createRecord. Override with care.Provided implementation of Mapper#wrap:
function (data, opts) { return this.createRecord(data, opts) }
Method parameters:Name Type Argument Description data
Object | Array.<Object> The record or records to be wrapped.
opts
Object <optional>
Configuration options. Passed to Mapper#createRecord.
Exampleconst PostMapper = new Mapper({ name: 'post', // Override to customize behavior wrap (data, opts) { const originalWrap = this.constructor.prototype.wrap // Let's say "GET /post" doesn't return JSON quite like JSData expects, // but the actual post records are nested under a "posts" field. So, // we override Mapper#wrap to handle this special case. if (opts.op === 'findAll') { return originalWrap.call(this, data.posts, opts) } // Otherwise perform original behavior return originalWrap.call(this, data, opts) } })
Type Definitions
-
afterCreateListener(props, opts, result)
-
Callback signature for the Mapper#event:afterCreate event.
Method parameters:Name Type Description props
Object The
props
argument passed to Mapper#afterCreate.opts
Object The
opts
argument passed to Mapper#afterCreate.result
Object The
result
argument passed to Mapper#afterCreate.Examplefunction onAfterCreate (props, opts, result) { // do something } store.on('afterCreate', onAfterCreate)
-
afterCreateManyListener(records, opts, result)
-
Callback signature for the Mapper#event:afterCreateMany event.
Method parameters:Name Type Description records
Object The
records
argument received by Mapper#afterCreateMany.opts
Object The
opts
argument received by Mapper#afterCreateMany.result
Object The
result
argument received by Mapper#afterCreateMany.Examplefunction onAfterCreateMany (records, opts, result) { // do something } store.on('afterCreateMany', onAfterCreateMany)
-
afterDestroyAllListener(query, opts, result)
-
Callback signature for the Mapper#event:afterDestroyAll event.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#afterDestroyAll.opts
Object The
opts
argument passed to Mapper#afterDestroyAll.result
Object The
result
argument passed to Mapper#afterDestroyAll.Examplefunction onAfterDestroyAll (query, opts, result) { // do something } store.on('afterDestroyAll', onAfterDestroyAll)
-
afterDestroyListener(id, opts, result)
-
Callback signature for the Mapper#event:afterDestroy event.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#afterDestroy.opts
Object The
opts
argument passed to Mapper#afterDestroy.result
Object The
result
argument passed to Mapper#afterDestroy.Examplefunction onAfterDestroy (id, opts, result) { // do something } store.on('afterDestroy', onAfterDestroy)
-
afterFindAllListener(query, opts, result)
-
Callback signature for the Mapper#event:afterFindAll event.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#afterFindAll.opts
Object The
opts
argument passed to Mapper#afterFindAll.result
Object The
result
argument passed to Mapper#afterFindAll.Examplefunction onAfterFindAll (query, opts, result) { // do something } store.on('afterFindAll', onAfterFindAll)
-
afterFindListener(id, opts, result)
-
Callback signature for the Mapper#event:afterFind event.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#afterFind.opts
Object The
opts
argument passed to Mapper#afterFind.result
Object The
result
argument passed to Mapper#afterFind.Examplefunction onAfterFind (id, opts, result) { // do something } store.on('afterFind', onAfterFind)
-
afterUpdateAllListener(props, query, opts, result)
-
Callback signature for the Mapper#event:afterUpdateAll event.
Method parameters:Name Type Description props
Object The
props
argument received by Mapper#afterUpdateAll.query
Object The
query
argument received by Mapper#afterUpdateAll.opts
Object The
opts
argument received by Mapper#afterUpdateAll.result
Object The
result
argument received by Mapper#afterUpdateAll.Examplefunction onAfterUpdateAll (props, query, opts, result) { // do something } store.on('afterUpdateAll', onAfterUpdateAll)
-
afterUpdateListener(id, props, opts, result)
-
Callback signature for the Mapper#event:afterUpdate event.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#afterUpdate.props
Object The
props
argument passed to Mapper#afterUpdate.opts
Object The
opts
argument passed to Mapper#afterUpdate.result
Object The
result
argument passed to Mapper#afterUpdate.Examplefunction onAfterUpdate (id, props, opts, result) { // do something } store.on('afterUpdate', onAfterUpdate)
-
afterUpdateManyListener(records, opts, result)
-
Callback signature for the Mapper#event:afterUpdateMany event.
Method parameters:Name Type Description records
Object The
records
argument received by Mapper#afterUpdateMany.opts
Object The
opts
argument received by Mapper#afterUpdateMany.result
Object The
result
argument received by Mapper#afterUpdateMany.Examplefunction onAfterUpdateMany (records, opts, result) { // do something } store.on('afterUpdateMany', onAfterUpdateMany)
-
beforeCreateListener(props, opts)
-
Callback signature for the Mapper#event:beforeCreate event.
Method parameters:Name Type Description props
Object The
props
argument passed to Mapper#beforeCreate.opts
Object The
opts
argument passed to Mapper#beforeCreate.Examplefunction onBeforeCreate (props, opts) { // do something } store.on('beforeCreate', onBeforeCreate)
-
beforeCreateManyListener(records, opts)
-
Callback signature for the Mapper#event:beforeCreateMany event.
Method parameters:Name Type Description records
Object The
records
argument received by Mapper#beforeCreateMany.opts
Object The
opts
argument received by Mapper#beforeCreateMany.Examplefunction onBeforeCreateMany (records, opts) { // do something } store.on('beforeCreateMany', onBeforeCreateMany)
-
beforeDestroyAllListener(query, opts)
-
Callback signature for the Mapper#event:beforeDestroyAll event.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#beforeDestroyAll.opts
Object The
opts
argument passed to Mapper#beforeDestroyAll.Examplefunction onBeforeDestroyAll (query, opts) { // do something } store.on('beforeDestroyAll', onBeforeDestroyAll)
-
beforeDestroyListener(id, opts)
-
Callback signature for the Mapper#event:beforeDestroy event.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#beforeDestroy.opts
Object The
opts
argument passed to Mapper#beforeDestroy.Examplefunction onBeforeDestroy (id, opts) { // do something } store.on('beforeDestroy', onBeforeDestroy)
-
beforeFindAllListener(query, opts)
-
Callback signature for the Mapper#event:beforeFindAll event.
Method parameters:Name Type Description query
Object The
query
argument passed to Mapper#beforeFindAll.opts
Object The
opts
argument passed to Mapper#beforeFindAll.Examplefunction onBeforeFindAll (query, opts) { // do something } store.on('beforeFindAll', onBeforeFindAll)
-
beforeFindListener(id, opts)
-
Callback signature for the Mapper#event:beforeFind event.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#beforeFind.opts
Object The
opts
argument passed to Mapper#beforeFind.Examplefunction onBeforeFind (id, opts) { // do something } store.on('beforeFind', onBeforeFind)
-
beforeUpdateAllListener(props, query, opts)
-
Callback signature for the Mapper#event:beforeUpdateAll event.
Method parameters:Name Type Description props
Object The
props
argument received by Mapper#beforeUpdateAll.query
Object The
query
argument received by Mapper#beforeUpdateAll.opts
Object The
opts
argument received by Mapper#beforeUpdateAll.Examplefunction onBeforeUpdateAll (props, query, opts) { // do something } store.on('beforeUpdateAll', onBeforeUpdateAll)
-
beforeUpdateListener(id, props, opts)
-
Callback signature for the Mapper#event:beforeUpdate event.
Method parameters:Name Type Description id
String | Number The
id
argument passed to Mapper#beforeUpdate.props
Object The
props
argument passed to Mapper#beforeUpdate.opts
Object The
opts
argument passed to Mapper#beforeUpdate.Examplefunction onBeforeUpdate (id, props, opts) { // do something } store.on('beforeUpdate', onBeforeUpdate)
-
beforeUpdateManyListener(records, opts)
-
Callback signature for the Mapper#event:beforeUpdateMany event.
Method parameters:Name Type Description records
Object The
records
argument received by Mapper#beforeUpdateMany.opts
Object The
opts
argument received by Mapper#beforeUpdateMany.Examplefunction onBeforeUpdateMany (records, opts) { // do something } store.on('beforeUpdateMany', onBeforeUpdateMany)
Events
-
afterCreate
-
Fired during Mapper#create. See Mapper~afterCreateListener for how to listen for this event.
-
afterCreateMany
-
Fired during Mapper#createMany. See Mapper~afterCreateManyListener for how to listen for this event.
-
afterDestroy
-
Fired during Mapper#destroy. See Mapper~afterDestroyListener for how to listen for this event.
-
afterDestroyAll
-
Fired during Mapper#destroyAll. See Mapper~afterDestroyAllListener for how to listen for this event.
-
afterFind
-
Fired during Mapper#find. See Mapper~afterFindListener for how to listen for this event.
-
afterFindAll
-
Fired during Mapper#findAll. See Mapper~afterFindAllListener for how to listen for this event.
-
afterUpdate
-
Fired during Mapper#update. See Mapper~afterUpdateListener for how to listen for this event.
-
afterUpdateAll
-
Fired during Mapper#updateAll. See Mapper~afterUpdateAllListener for how to listen for this event.
-
afterUpdateMany
-
Fired during Mapper#updateMany. See Mapper~afterUpdateManyListener for how to listen for this event.
-
beforeCreate
-
Fired during Mapper#create. See Mapper~beforeCreateListener for how to listen for this event.
-
beforeCreateMany
-
Fired during Mapper#createMany. See Mapper~beforeCreateManyListener for how to listen for this event.
-
beforeDestroy
-
Fired during Mapper#destroy. See Mapper~beforeDestroyListener for how to listen for this event.
-
beforeDestroyAll
-
Fired during Mapper#destroyAll. See Mapper~beforeDestroyAllListener for how to listen for this event.
-
beforeFind
-
Fired during Mapper#find. See Mapper~beforeFindListener for how to listen for this event.
-
beforeFindAll
-
Fired during Mapper#findAll. See Mapper~beforeFindAllListener for how to listen for this event.
-
beforeUpdate
-
Fired during Mapper#update. See Mapper~beforeUpdateListener for how to listen for this event.
-
beforeUpdateAll
-
Fired during Mapper#updateAll. See Mapper~beforeUpdateAllListener for how to listen for this event.
-
beforeUpdateMany
-
Fired during Mapper#updateMany. See Mapper~beforeUpdateManyListener for how to listen for this event.