Class: Mapper

Mapper


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.)

Method parameters:
Name Type Description
opts Object

Configuration options.

Properties
Name Type Argument Default Description
applySchema Boolean <optional>
true

See Mapper#applySchema.

debug Boolean <optional>
false

See Mapper#debug.

defaultAdapter String <optional>
http

See Mapper#defaultAdapter.

idAttribute String <optional>
id

See Mapper#idAttribute.

name String

See Mapper#name.

notify Boolean <optional>

See Mapper#notify.

raw Boolean <optional>
false

See Mapper#raw.

recordClass Function | Boolean <optional>

See Mapper#recordClass.

Return value:
Type Description
Mapper

A new Mapper instance.

Examples

Import and instantiate

import {Mapper} from 'js-data'

const UserService = 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.

Details
Since Default value Source Tutorials
3.0.0
{}
Mapper.js, line 121

_listeners

Event listeners attached to this Component. Do not modify. Use Component#on and Component#off instead.

Details
Type 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.

Details
Type Since Default value Source
Boolean 3.0.0
true
Mapper.js, line 132

debug

Whether to enable debug-level logs.

Details
Type Since Default value Source
Boolean 3.0.0
false
Mapper.js, line 146

defaultAdapter

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

Details
Type Since Default value Source Tutorials
String 3.0.0
"http"
Mapper.js, line 156

idAttribute

The field used as the unique identifier on records handled by this Mapper.

Details
Type Since Default value Source
String 3.0.0
id
Mapper.js, line 167

lifecycleMethods

The meta information describing this Mapper's available lifecycle methods. Do not modify.

TODO: Improve documentation.

Details
Type Since Source
Object 3.0.0 Mapper.js, line 321

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.

Details
Type Since Source
String 3.0.0 Mapper.js, line 354

notify

Whether this Mapper should emit operational events.

Details
Type Since Default value Source
Boolean 3.0.0
true
Mapper.js, line 177

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.

Details
Type Since Default value Source
Boolean 3.0.0
false
Mapper.js, line 187

recordClass

Set to false to force the Mapper to work with POJO objects only.

Details
Since Default value Source See
3.0.0
Record
Mapper.js, line 268
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.

Details
Type Since Source See
Schema 3.0.0 Mapper.js, line 335

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.

Details
Since Source
3.0.0 Mapper.js, line 1811
Examples

Extend the class in a cross-browser manner.

import {Mapper} from 'js-data'
const CustomMapperClass = Mapper.extend({
  foo () { return 'bar' }
})
const customMapper = new CustomMapperClass({ name: 'test' })
console.log(customMapper.foo()) // "bar"

Extend the class using ES2015 class syntax.

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.

Details
Since Source
3.0.0 Mapper.js, line 401

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.

Details
Since Source
3.0.0 Mapper.js, line 414

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.

Details
Since Source
3.0.0 Mapper.js, line 427

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.

Details
Since Source
3.0.0 Mapper.js, line 440

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.

Details
Since Source
3.0.0 Mapper.js, line 453

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.

Details
Since Source
3.0.0 Mapper.js, line 467

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.

Details
Since Source
3.0.0 Mapper.js, line 480

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.

Details
Since Source
3.0.0 Mapper.js, line 493

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.

Details
Since Source
3.0.0 Mapper.js, line 506

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.

Details
Since Source
3.0.0 Mapper.js, line 520

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.

Details
Since Source
3.0.0 Mapper.js, line 534

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.

Details
Since Source
3.0.0 Mapper.js, line 571

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.

Details
Since Source
3.0.0 Mapper.js, line 547

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.

Details
Since Source
3.0.0 Mapper.js, line 559

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.

Details
Since Source
3.0.0 Mapper.js, line 583

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.

Details
Since Source
3.0.0 Mapper.js, line 595

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.

Details
Since Source
3.0.0 Mapper.js, line 607

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.

Details
Since Source
3.0.0 Mapper.js, line 619

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.

Details
Since Source
3.0.0 Mapper.js, line 631

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.

Details
Since Source
3.0.0 Mapper.js, line 644

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.

Details
Since Source
3.0.0 Mapper.js, line 657

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.

Details
Since Source
3.0.0 Mapper.js, line 670

belongsTo()

Define a belongsTo relationship. Only useful if you're managing your Mappers manually and not using a Container or DataStore component.

Example
PostService.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.

Details
Since Source
3.0.0 Mapper.js, line 747
Example

Get the number of published blog posts

PostService.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.

Details
Since Source
3.0.0 Mapper.js, line 777
Example

Create and save a new blog post

PostService.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.

Details
Since Source See
3.0.0 Mapper.js, line 903
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.

Details
Since Source Tutorials
3.0.0 Mapper.js, line 917
Example

Create and save several new blog posts

PostService.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 if props 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.

Return value:
Type Description
Record | Array.<Record>

The Record instance or Record instances.

Details
Since Source
3.0.0 Mapper.js, line 1046
Examples

Create empty unsaved record instance

const post = PostService.createRecord()

Create an unsaved record instance with inital properties

const post = PostService.createRecord({
  title: 'Modeling your data',
  status: 'draft'
})

Create a record instance that corresponds to a saved record

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'
})

Create record instances from an array

const posts = PostService.createRecord([{
  title: 'Modeling your data',
  status: 'draft'
}, {
  title: 'Reading data',
  status: 'draft'
}])

Records are validated by default

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' }]
}

Skip validation

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
Details
Since Source
3.0.0 Mapper.js, line 1140

dbg(args)

Log the provided values at the "debug" level.

Method parameters:
Name Type Argument Description
args * <optional>
<repeatable>

Values to log.

Details
Since 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.

Details
Since Source Tutorials
3.0.0 Mapper.js, line 1200
Examples

Destroy a specific blog post

PostService.destroy(1234).then(() => {
  // Blog post #1234 has been destroyed
})

Get full response

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 no query 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.

Details
Since Source Tutorials See
3.0.0 Mapper.js, line 1234
Examples

Destroy all blog posts

PostService.destroyAll().then(() => {
  // All blog posts have been destroyed
})

Destroy all "draft" blog posts

PostService.destroyAll({ status: 'draft' }).then(() => {
  // All "draft" blog posts have been destroyed
})

Get full response

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.

Details
Since Source
3.0.0 Component.js, line 98
Inherited From:
Examples
collection.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.

Examples
PostService.find(1).then((post) => {
  console.log(post) // { id: 1, ...}
})

Get full response

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.

Details
Since Source Tutorials See
3.0.0 Mapper.js, line 1318
Examples

Find all "published" blog posts

PostService.findAll({ status: 'published' }).then((posts) => {
  console.log(posts) // [{ id: 1, status: 'published', ...}, ...]
})

Get full response

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.

Details
Since Source Tutorials
3.0.0 Mapper.js, line 1358

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.

Details
Since Source Tutorials
3.0.0 Mapper.js, line 1377

getAdapters()

Get the object of registered adapters for this Mapper.

Return value:
Type Description
Object

Mapper#_adapters

Details
Since Source Tutorials
3.0.0 Mapper.js, line 1395

getSchema()

Returns this Mapper's Schema.

Return value:
Type Description
Schema

This Mapper's Schema.

Details
Since Source See
3.0.0 Mapper.js, line 1407

hasMany()

Defines a hasMany relationship. Only useful if you're managing your Mappers manually and not using a Container or DataStore component.

Example
UserService.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.

Example
UserService.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.

Method parameters:
Name Type Description
record Object | Record

The record to check.

Return value:
Type Description
Boolean

Whether record is an instance of this Mapper's Mapper#recordClass.

Details
Since Source
3.0.0 Mapper.js, line 1459
Example
const 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.

Details
Since 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.

Details
Since Source
3.0.0 Component.js, line 79
Inherited From:
Examples

Remove a listener to a single event

collection.off('add', handler)

Remove all listeners to a single 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.

Details
Since Source
3.0.0 Component.js, line 49
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.

Details
Since Source Tutorials
3.0.0 Mapper.js, line 1480

sum(field, query, opts)

Select records according to the query argument, and aggregate the sum value of the property specified by field.

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.

Details
Since Source
3.0.0 Mapper.js, line 1501
Example
PurchaseOrderService.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.

Details
Since Source
3.0.0 Mapper.js, line 1533
Example
import {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.

Details
Since Source Tutorials
3.0.0 Mapper.js, line 1617
Example

Update a specific post

PostService.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.

Details
Since Source Tutorials See
3.0.0 Mapper.js, line 1651
Example

Turn all of John's blog posts into drafts.

const 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.

Details
Since Source Tutorials
3.0.0 Mapper.js, line 1687
Example
PostService.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.

Return value:
Type Description
Array.<Object>

Array of errors or undefined if no errors.

Details
Since Source
3.0.0 Mapper.js, line 1720
Example
import {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.

Return value:
Type Description
Record | Array.<Record>

The wrapped record or records.

Details
Since Source
3.0.0 Mapper.js, line 1769
Example

Override to customize behavior

const 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)
  }
})