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 {Mapper} from 'js-data'
const UserService = new Mapper({ name: 'user' })
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 7 - Inherited From:
-
applySchema
-
Whether to augment Mapper#recordClass with getter/setter property accessors 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. -
debug
-
Whether to enable debug-level logs.
-
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.
TODO: Improve documentation.
-
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.Examplesimport {Mapper, Record} from 'js-data' const UserMapper = new Mapper({ recordClass: false }) UserMapper.recordClass // false const user = UserMapper#createRecord() user instanceof Record // false
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
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.
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.
classProps
Object <optional>
{} Static properties to add to the subclass.
Return value:Type Description Constructor Subclass of this Mapper.
Examplesimport {Mapper} from 'js-data' const CustomMapperClass = Mapper.extend({ foo () { return 'bar' } }) const customMapper = new CustomMapperClass({ name: 'test' }) console.log(customMapper.foo()) // "bar"
class CustomMapperClass extends Mapper { foo () { return 'bar' } } const customMapper = new CustomMapperClass({ name: 'test' }) console.log(customMapper.foo()) // "bar"
-
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.
ExamplePostService.belongsTo(UserService, { // post.user_id points to user.id foreignKey: 'user_id' // user records will be attached to post records at "post.user" localField: 'user' }) CommentService.belongsTo(UserService, { // comment.user_id points to user.id foreignKey: 'user_id' // user records will be attached to comment records at "comment.user" localField: 'user' }) CommentService.belongsTo(PostService, { // 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.
ExamplePostService.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.
Return value:Type Description Promise Resolves with the created record.
ExamplePostService.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.
Return value:Type Description Promise Resolves with the created records.
ExamplePostService.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.
Examplesconst post = PostService.createRecord()
const post = PostService.createRecord({ title: 'Modeling your data', status: 'draft' })
const post = PostService.createRecord({ // JSData thinks this record has been saved if it has a primary key id: 1234, title: 'Modeling your data', status: 'draft' })
const posts = PostService.createRecord([{ title: 'Modeling your data', status: 'draft' }, { title: 'Reading data', status: 'draft' }])
import {Mapper} from 'js-data' const PostService = new Mapper({ name: 'post', schema: { properties: { title: { type: 'string' } } } }) try { const post = PostService.createRecord({ title: 1234, }) } catch (err) { console.log(err.errors) // [{ expected: 'one of (string)', actual: 'number', path: 'title' }] }
import {Mapper} from 'js-data' const PostService = new Mapper({ name: 'post', schema: { properties: { title: { type: 'string' } } } }) const post = PostService.createRecord({ title: 1234, }, { noValidate: true }) console.log(post.isValid()) // false
-
crud(method, args)
-
Lifecycle invocation method.
TODO: Improve documentation for this method.
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.
Method parameters:Name Type Argument Description args
* <optional>
<repeatable>
Values to log.
DetailsSince Source 3.0.0 Component.js, line 32 - 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.
Return value:Type Description Promise Resolves when the record has been destroyed. Resolves even if no record was found to be destroyed.
ExamplesPostService.destroy(1234).then(() => { // Blog post #1234 has been destroyed })
PostService.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.
Return value:Type Description Promise Resolves when the records have been destroyed. Resolves even if no records were found to be destroyed.
ExamplesPostService.destroyAll().then(() => { // All blog posts have been destroyed })
PostService.destroyAll({ status: 'draft' }).then(() => { // All "draft" blog posts have been destroyed })
const query = null const options = { raw: true } PostService.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 98 - Inherited From:
Examplescollection.on('foo', (msg) => { console.log(msg) // "bar" }) collection.emit('foo', 'bar')
store.on('foo', (msg, val1, val2) => { console.log(msg, val1, val2) // "bar" "beep" "boop" }) store.emit('foo', 'bar', '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.
Return value:Type Description Promise Resolves with the found record. Resolves with
undefined
if no record was found.ExamplesPostService.find(1).then((post) => { console.log(post) // { id: 1, ...} })
PostService.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.
Return value:Type Description Promise Resolves with the found records, if any.
ExamplesPostService.findAll({ status: 'published' }).then((posts) => { console.log(posts) // [{ id: 1, status: 'published', ...}, ...] })
PostService.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.
ExampleUserService.hasMany(PostService, { // 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.
ExampleUserService.hasOne(ProfileService, { // 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 = PostService.createRecord() console.log(PostService.is(post)) // true // Equivalent to what's above console.log(post instanceof PostService.recordClass) // true
-
log(level, args)
-
Log the provided values. By default sends values to
console[level]
.Method parameters:Name Type Argument Description level
String Log level
args
* <optional>
<repeatable>
Values to log.
DetailsSince Source 3.0.0 Component.js, line 39 - 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 79 - Inherited From:
Examplescollection.off('add', handler)
record.off('change')
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 49 - Inherited From:
Examplesstore.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 })
collection.on('add', (records) => { console.log(records) // [...] })
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.
ExamplePurchaseOrderService.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 include 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 PersonService = new Mapper({ name: 'person', schema: { properties: { name: { type: 'string' }, id: { type: 'string' } } } }) const person = PersonService.createRecord({ id: 1, name: 'John', foo: 'bar' }) console.log(PersonService.toJSON(person)) // {"id":1,"name":"John","foo":"bar"} console.log(PersonService.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.
Return value:Type Description Promise Resolves with the updated record. Rejects if the record could not be found.
ExamplePostService.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.
Return value:Type Description Promise Resolves with the update records, if any.
Exampleconst update = { status: draft: published_at: null } const query = { userId: 1234 } PostService.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.
Return value:Type Description Promise Resolves with the updated records. Rejects if any of the records could be found.
ExamplePostService.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 PersonService = new Mapper({ name: 'person', schema: PersonSchema }) let errors = PersonService.validate({ name: 'John' }) console.log(errors) // undefined errors = PersonService.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', 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) } })