var app = loopback()

LoopBackApplication

The App object represents a Loopback application.

The App object extends Express and supports Express / Connect middleware. See Express documentation for details.

var loopback = require('loopback');
var app = loopback();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);

app.remotes()

Lazily load a set of remote objects.

NOTE: Calling app.remotes() more than once returns only a single set of remote objects.

Returns
Name Type Description
result RemoteObjects

app.model(Model, config)

Attach a model to the app. The Model will be available on the app.models object.

// Attach an existing model
var User = loopback.User;
app.model(User);

// Attach an existing model, alter some aspects of the model
var User = loopback.User;
app.model(User, { dataSource: 'db' });

// LoopBack 1.x way: create and attach a new model (deprecated)
var Widget = app.model('Widget', {
  dataSource: 'db',
  properties: {
    name: 'string'
  }
});
Arguments
Name Type Description
Model Object or String

The model to attach.

config Object

The model's configuration.

config
Name Type Description
dataSource String or DataSource

The DataSource to which to attach the model.

[public] Boolean

whether the model should be exposed via REST API

[relations] Object

relations to add/update

Returns
Name Type Description
result ModelConstructor

the model class

app.models()

Get the models exported by the app. Returns only models defined using app.model()

There are two ways to access models:

  1. Call app.models() to get a list of all models.
var models = app.models();

models.forEach(function (Model) {
 console.log(Model.modelName); // color
});

**2. Use app.model to access a model by name. app.model has properties for all defined models.

The following example illustrates accessing the Product and CustomerReceipt models using the models object.

var loopback = require('loopback');
 var app = loopback();
 app.boot({
  dataSources: {
    db: {connector: 'memory'}
  }
});

app.model('product', {dataSource: 'db'});
app.model('customer-receipt', {dataSource: 'db'});

// available based on the given name
var Product = app.models.Product;

// also available as camelCase
var product = app.models.product;

// multi-word models are avaiable as pascal cased
var CustomerReceipt = app.models.CustomerReceipt;

// also available as camelCase
var customerReceipt = app.models.customerReceipt;
Returns
Name Type Description
result Array

Array of model classes.

app.dataSource(name, config)

Define a DataSource.

Arguments
Name Type Description
name String

The data source name

config Object

The data source config

app.connector(name, connector)

Register a connector.

When a new data-source is being added via app.dataSource, the connector name is looked up in the registered connectors first.

Connectors are required to be explicitly registered only for applications using browserify, because browserify does not support dynamic require, which is used by LoopBack to automatically load the connector module.

Arguments
Name Type Description
name String

Name of the connector, e.g. 'mysql'.

connector Object

Connector object as returned by require('loopback-connector-{name}').

app.remoteObjects()

Get all remote objects.

Returns
Name Type Description
result Object

Remote objects.

app.dataSources

An object to store dataSource instances.

app.enableAuth()

Enable app wide authentication.

app.listen(cb)

Listen for connections and update the configured port.

When there are no parameters or there is only one callback parameter, the server will listen on app.get('host') and app.get('port').

// listen on host/port configured in app config
app.listen();

Otherwise all arguments are forwarded to http.Server.listen.

// listen on the specified port and all hosts, ignore app config
app.listen(80);

The function also installs a listening callback that calls app.set('port') with the value returned by server.address().port. This way the port param contains always the real port number, even when listen was called with port number 0.

Arguments
Name Type Description
cb Function

If specified, the callback is added as a listener for the server's "listening" event.

Returns
Name Type Description
result http.Server

A node http.Server with this application configured as the request handler.

loopback

loopback

Main entry for LoopBack core module. It provides static properties and methods to create models and data sources. The module itself is a function that creates loopback app. For example,

var loopback = require('loopback');
var app = loopback();

loopback.version

Framework version.

loopback.mime

Expose mime.

loopback.remoteMethod(fn, options)

Add a remote method to a model.

Arguments
Name Type Description
fn Function
options Object

(optional)

loopback.template(path)

Create a template helper.

var render = loopback.template('foo.ejs');
var html = render({foo: 'bar'});
Arguments
Name Type Description
path String

Path to the template file.

Returns
Name Type Description
result Function

loopback.isBrowser

True if running in a browser environment; false otherwise.

loopback.isServer

True if running in a server environment; false otherwise.

loopback.createModel

Create a named vanilla JavaScript class constructor with an attached set of properties and options.

This function comes with two variants:

  • loopback.createModel(name, properties, options)
  • loopback.createModel(config)

In the second variant, the parameters name, properties and options are provided in the config object. Any additional config entries are interpreted as options, i.e. the following two configs are identical:

{ name: 'Customer', base: 'User' }
{ name: 'Customer', options: { base: 'User' } }

Example

Create an Author model using the three-parameter variant:

loopback.createModel(
  'Author',
  {
    firstName: 'string',
    lastName: 'string
  },
  {
    relations: {
      books: {
        model: 'Book',
        type: 'hasAndBelongsToMany'
      }
    }
  }
);

Create the same model using a config object:

loopback.createModel({
  name: 'Author',
  properties: {
    firstName: 'string',
    lastName: 'string
  },
  relations: {
    books: {
      model: 'Book',
      type: 'hasAndBelongsToMany'
    }
  }
});
Arguments
Name Type Description
name String

Unique name.

properties Object
options Object

(optional)

loopback.configureModel(ModelCtor, config)

Alter an existing Model class.

Arguments
Name Type Description
ModelCtor Model

The model constructor to alter.

config Object

Additional configuration to apply

config
Name Type Description
dataSource DataSource

Attach the model to a dataSource.

[relations] Object

Model relations to add/update.

loopback.findModel(modelName)

Look up a model class by name from all models created by loopback.createModel()

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result Model

The model class

loopback.getModel(modelName)

Look up a model class by name from all models created by loopback.createModel(). Throw an error when no such model exists.

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result Model

The model class

loopback.getModelByType(modelType)

Look up a model class by the base model class. The method can be used by LoopBack to find configured models in models.json over the base model.

Arguments
Name Type Description
modelType Model

The base model class

Returns
Name Type Description
result Model

The subclass if found or the base class

loopback.createDataSource(name, options)

Create a data source with passing the provided options to the connector.

Arguments
Name Type Description
name String

Optional name.

options Object

Data Source options

options
Name Type Description
connector Object

LoopBack connector.

[*] *

Other connector properties. See the relevant connector documentation.

loopback.memory()

Get an in-memory data source. Use one if it already exists.

Arguments
Name Type Description
[name] String

The name of the data source. If not provided, the 'default' is used.

loopback.setDefaultDataSourceForType(type, dataSource)

Set the default dataSource for a given type.

Arguments
Name Type Description
type String

The datasource type

dataSource Object or DataSource

The data source settings or instance

Returns
Name Type Description
result DataSource

The data source instance

loopback.getDefaultDataSourceForType()

Get the default dataSource for a given type.

Arguments
Name Type Description
type String

The datasource type

Returns
Name Type Description
result DataSource

The data source instance

loopback.autoAttach()

Attach any model that does not have a dataSource to the default dataSource for the type the Model requests

Base models

model = new Model

The base class for all models.

Inheriting from Model

var properties = {...};
var options = {...};
var MyModel = loopback.Model.extend('MyModel', properties, options);

Options

  • trackChanges - If true, changes to the model will be tracked. Required for replication.

Events

Event: changed

Emitted after a model has been successfully created, saved, or updated.

MyModel.on('changed', function(inst) {
  console.log('model with id %s has been changed', inst.id);
  // => model with id 1 has been changed
});

Event: deleted

Emitted after an individual model has been deleted.

MyModel.on('deleted', function(inst) {
  console.log('model with id %s has been deleted', inst.id);
  // => model with id 1 has been deleted
});

Event: deletedAll

Emitted after an individual model has been deleted.

MyModel.on('deletedAll', function(where) {
  if(where) {
    console.log('all models where', where, 'have been deleted');
    // => all models where
    // => {price: {gt: 100}}
    // => have been deleted
  }
});

Event: attached

Emitted after a Model has been attached to an app.

Event: dataSourceAttached

Emitted after a Model has been attached to a DataSource.

Arguments
Name Type Description
data Object

Model.checkAccess(token, modelId, sharedMethod, callback)

Check if the given access token can invoke the method

Arguments
Name Type Description
token AccessToken

The access token

modelId Any

The model ID.

sharedMethod SharedMethod

The method in question

callback Function

The callback function

callback
Name Type Description
err String or Error

The error object

allowed Boolean

True if the request is allowed; false otherwise.

Model.getApp(callback)

Get the Application the Model is attached to.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
app Application

Model.remoteMethod(name, options)

Enable remote invocation for the method with the given name.

Arguments
Name Type Description
name String

The name of the method. ```js // static method example (eg. Model.myMethod()) Model.remoteMethod('myMethod');

options Object

The remoting options. See loopback.remoteMethod()) for details.

persistedModel = new PersistedModel

PersistedModel

Extends Model with basic query and CRUD support.

Change Event

Listen for model changes using the change event.

MyPersistedModel.on('changed', function(obj) {
   console.log(obj) // => the changed model
});
Arguments
Name Type Description
data Object
data.id Number

The default id property

PersistedModel.create([optional], obj))

Create new instance of Model class, saved in database

Arguments
Name Type Description
[optional] data
obj) callback(err or

callback called with arguments:

  • err (null or Error)
  • instance (null or Model)

PersistedModel.upsert

Update or insert a model instance

Arguments
Name Type Description
data Object

The model instance data

[callback] Function

The callback function

PersistedModel.findOrCreate(query, data, cb)

Find one record, same as find, limited by 1 and return object, not collection, if not found, create using data provided as second argument

Arguments
Name Type Description
query Object

search conditions: {where: {test: 'me'}}.

data Object

object to create.

cb Function

callback called with (err, instance)

PersistedModel.exists(id, cb)

Check whether a model instance exists in database

Arguments
Name Type Description
id id

identifier of object (primary key value)

cb Function

callbacl called with (err, exists: Bool)

PersistedModel.findById(id, cb)

Find object by id

Arguments
Name Type Description
id Any

primary key value

cb Function

callback called with (err, instance)

PersistedModel.find(params, callback)

Find all instances of Model, matched by query make sure you have marked as index: true fields for filter or sort

Arguments
Name Type Description
params Object

(optional)

  • where: Object { key: val, key2: {gt: 'val2'}}
  • include: String, Object or Array. See PersistedModel.include documentation.
  • order: String
  • limit: Number
  • skip: Number
callback Function

(required) called with arguments:

  • err (null or Error)
  • Array of instances

PersistedModel.findOne(params, cb)

Find one record, same as all, limited by 1 and return object, not collection

Arguments
Name Type Description
params Object

search conditions: {where: {test: 'me'}}

cb Function

callback called with (err, instance)

PersistedModel.count(where, cb)

Return count of matched records

Arguments
Name Type Description
where Object

search conditions (optional)

cb Function

callback, called with (err, count)

persistedModel.save({validate:, obj))

Save instance. When instance haven't id, create method called instead. Triggers: validate, save, update | create

Arguments
Name Type Description
{validate: options

true, throws: false} [optional]

obj) callback(err or

persistedModel.isNewRecord()

Determine if the data model is new.

Returns
Name Type Description
result Boolean

persistedModel.updateAttribute(name, value, callback)

Update single attribute

equals to `updateAttributes({name: value}, cb)

Arguments
Name Type Description
name String

name of property

value Mixed

value of property

callback Function

callback called with (err, instance)

persistedModel.updateAttributes(data, callback)

Update set of attributes

this method performs validation before updating

Arguments
Name Type Description
data Object

data to update

callback Function

callback called with (err, instance)

persistedModel.reload(callback)

Reload object from persistence

Arguments
Name Type Description
callback Function

called with (err, instance) arguments

persistedModel.setId(val)

Set the correct id property for the PersistedModel. If a Connector defines a setId method it will be used. Otherwise the default lookup is used. You should override this method to handle complex ids.

Arguments
Name Type Description
val Any

The id value. Will be converted to the type the id property specifies.

persistedModel.getId()

Get the id value for the PersistedModel.

Returns
Name Type Description
result Any

The id value

persistedModel.getIdName()

Get the id property name of the constructor.

Returns
Name Type Description
result String

The id property name

PersistedModel.getIdName()

Get the id property name of the constructor.

Returns
Name Type Description
result String

The id property name

PersistedModel.diff(since, remoteChanges, callback)

Get a set of deltas and conflicts since the given checkpoint.

See Change.diff() for details.

Arguments
Name Type Description
since Number

Find deltas since this checkpoint

remoteChanges Array

An array of change objects

callback Function

PersistedModel.changes(since, filter, callback)

Get the changes to a model since a given checkpoint. Provide a filter object to reduce the number of results returned.

Arguments
Name Type Description
since Number

Only return changes since this checkpoint

filter Object

Only include changes that match this filter (same as Model.find(filter, ...))

callback Function
callback
Name Type Description
err Error
changes Array

An array of Change objects

PersistedModel.checkpoint(callback)

Create a checkpoint.

Arguments
Name Type Description
callback Function

PersistedModel.currentCheckpoint(callback)

Get the current checkpoint id.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
currentCheckpointId Number

PersistedModel.replicate([since], targetModel, [options], [callback])

Replicate changes since the given checkpoint to the given target model.

Arguments
Name Type Description
[since] Number

Since this checkpoint

targetModel Model

Target this model class

[options] Object
[options.filter] Object

Replicate models that match this filter

[callback] Function
[callback]
Name Type Description
err Error
conflicts Conflict[]

A list of changes that could not be replicated due to conflicts.

PersistedModel.createUpdates(deltas, callback)

Create an update list (for Model.bulkUpdate()) from a delta list (result of Change.diff()).

Arguments
Name Type Description
deltas Array
callback Function

PersistedModel.bulkUpdate(updates, callback)

Apply an update list.

Note: this is not atomic

Arguments
Name Type Description
updates Array

An updates list (usually from Model.createUpdates())

callback Function

PersistedModel.getChangeModel()

Get the Change model.

PersistedModel.getSourceId(callback)

Get the source identifier for this model / dataSource.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
sourceId String

PersistedModel.enableChangeTracking()

Enable the tracking of changes made to the model. Usually for replication.

PersistedModel.handleChangeError(err)

Handle a change error. Override this method in a subclassing model to customize change error handling.

Arguments
Name Type Description
err Error

PersistedModel.rectifyChange(id, callback)

Tell loopback that a change to the model with the given id has occurred.

Arguments
Name Type Description
id Any

The id of the model that has changed

callback Function
callback
Name Type Description
err Error

Middleware

loopback.rest()

Expose models over REST.

For example:

app.use(loopback.rest());

For more information, see Exposing models over a REST API.

loopback.status()

Return HTTP response with basic application status information: date the application was started and uptime, in JSON format. For example:

{
 "started": "2014-06-05T00:26:49.750Z",
 "uptime": 9.394
}

loopback.token([options])

Check for an access token in cookies, headers, and query string parameters. This function always checks for the following:

  • access_token (params only)
  • X-Access-Token (headers only)
  • authorization (headers and cookies)

It checks for these values in cookies, headers, and query string parameters in addition to the items specified in the options parameter.

NOTE: This function only checks for signed cookies.

The following example illustrates how to check for an accessToken in a custom cookie, query string parameter and header called foo-auth.

app.use(loopback.token({
  cookies: ['foo-auth'],
  headers: ['foo-auth', 'X-Foo-Auth'],
  params: ['foo-auth', 'foo_auth']
}));
Arguments
Name Type Description
[options] Object

Each option array is used to add additional keys to find an accessToken for a request.

[options]
Name Type Description
[cookies] Array

Array of cookie names.

[headers] Array

Array of header names.

[params] Array

Array of param names.

[model] Array

An AccessToken object to use.

loopback.urlNotFound()

Convert any request not handled so far to a 404 error to be handled by error-handling middleware.

Built-in models

accessToken = new AccessToken

Token based authentication and access control.

AccessToken.ANONYMOUS

Anonymous Token

assert(AccessToken.ANONYMOUS.id === '$anonymous');

AccessToken.createAccessTokenId(callback)

Create a cryptographically random access token id.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
token String

AccessToken.findForRequest(req, [options], callback)

Find a token for the given ServerRequest.

Arguments
Name Type Description
req ServerRequest
[options] Object

Options for finding the token

callback Function
callback
Name Type Description
err Error
token AccessToken

accessToken.validate(callback)

Validate the token.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
isValid Boolean

ACLSchema

System grants permissions to principals (users/applications, can be grouped into roles).

Protected resource: the model data and operations (model/property/method/relation/…)

For a given principal, such as client application and/or user, is it allowed to access (read/write/execute) the protected resource?

ACL

A Model for access control meta data.

ACL.getMatchingScore(rule, req)

Calculate the matching score for the given rule and request

Arguments
Name Type Description
rule ACL

The ACL entry

req AccessRequest

The request

Returns
Name Type Description
result Number

aCL.score(req)

Get matching score for the given AccessRequest.

Arguments
Name Type Description
req AccessRequest

The request

Returns
Name Type Description
result Number

score

ACL.checkPermission(principalType, principalId, model, property, accessType, callback)

Check if the given principal is allowed to access the model/property

Arguments
Name Type Description
principalType String

The principal type.

principalId String

The principal ID.

model String

The model name.

property String

The property/method/relation name.

accessType String

The access type.

callback Function

Callback function.

callback
Name Type Description
err String or Error

The error object

result AccessRequest

The access permission

ACL.checkAccessForContext(context, callback)

Check if the request has the permission to access.

Arguments
Name Type Description
context Object

See below.

callback Function

Callback function

context
Name Type Description
principals Object[]

An array of principals.

model String or Model

The model name or model class.

id *

The model instance ID.

property String

The property/method/relation name.

accessType String

The access type: READE, WRITE, or EXEC.

ACL.checkAccessForToken(token, model, modelId, method, callback)

Check if the given access token can invoke the method

Arguments
Name Type Description
token AccessToken

The access token

model String

The model name

modelId Any

The model id

method String

The method name

callback Function

Callback function

callback
Name Type Description
err String or Error

The error object

allowed Boolean

is the request allowed

scope = new Scope

Resource owner grants/delegates permissions to client applications

For a protected resource, does the client application have the authorization from the resource owner (user or system)?

Scope has many resource access entries

Scope.checkPermission(scope, model, property, accessType, callback)

Check if the given scope is allowed to access the model/property

Arguments
Name Type Description
scope String

The scope name

model String

The model name

property String

The property/method/relation name

accessType String

The access type

callback Function
callback
Name Type Description
err String or Error

The error object

result AccessRequest

The access permission

application = new Application

Manage client applications and organize their users.

Application.register(owner, name, options, callback)

Register a new application

Arguments
Name Type Description
owner String

Owner's user ID.

name String

Name of the application

options Object

Other options

callback Function

Callback function

application.resetKeys(callback)

Reset keys for the application instance

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error

Application.resetKeys(appId, callback)

Reset keys for a given application by the appId

Arguments
Name Type Description
appId Any
callback Function
callback
Name Type Description
err Error

Application.authenticate(appId, key, callback)

Authenticate the application id and key.

matched parameter is one of:

  • clientKey
  • javaScriptKey
  • restApiKey
  • windowsKey
  • masterKey
Arguments
Name Type Description
appId Any
key String
callback Function
callback
Name Type Description
err Error
matched String

The matching key

email = new Email

The Email Model.

Properties

  • to - String (required)
  • from - String (required)
  • subject - String (required)
  • text - String
  • html - String

email.send(options, callback)

Send an email with the given options.

Example Options:

{
  from: "Fred Foo <[email protected]>", // sender address
  to: "[email protected], [email protected]", // list of receivers
  subject: "Hello", // Subject line
  text: "Hello world", // plaintext body
  html: "<b>Hello world</b>" // html body
}

See https://github.com/andris9/Nodemailer for other supported options.

Arguments
Name Type Description
options Object

See below

callback Function

Called after the e-mail is sent or the sending failed

options
Name Type Description
from String

Senders's email address

to String

List of one or more recipient email addresses (comma-delimited)

subject String

Subject line

text String

Body text

html String

Body HTML (optional)

roleMapping = new RoleMapping

The RoleMapping model extends from the built in loopback.Model type.

roleMapping.application(callback)

Get the application principal

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
application Application

roleMapping.user(callback)

Get the user principal

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
user User

roleMapping.childRole(callback)

Get the child role principal

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
childUser User

role = new Role

The Role Model

Role.registerResolver(, The)

Add custom handler for roles

Arguments
Name Type Description
role
The resolver

resolver function decides if a principal is in the role dynamically

function(role, context, callback)

Role.isOwner(modelClass, modelId, userId, callback)

Check if a given userId is the owner the model instance

Arguments
Name Type Description
modelClass Function

The model class

modelId Any

The model id

userId *)

The user id

callback Function

Role.isAuthenticated(context, callback)

Check if the user id is authenticated

Arguments
Name Type Description
context Object

The security context

callback Function
callback
Name Type Description
err Error
isAuthenticated Boolean

Role.isInRole(role, context, callback)

Check if a given principal is in the role

Arguments
Name Type Description
role String

The role name

context Object

The context object

callback Function
callback
Name Type Description
err Error
isInRole Boolean

Role.getRoles(context, callback, callback)

List roles for a given principal

Arguments
Name Type Description
context Object

The security context

callback Function
callback Function
callback
Name Type Description
err
An String[]

array of role ids

user = new User

Extends from the built in loopback.Model type.

Default User ACLs.

  • DENY EVERYONE *
  • ALLOW EVERYONE create
  • ALLOW OWNER deleteById
  • ALLOW EVERYONE login
  • ALLOW EVERYONE logout
  • ALLOW EVERYONE findById
  • ALLOW OWNER updateAttributes

user.createAccessToken(ttl, err, token)

Create access token for the logged in user. This method can be overridden to customize how access tokens are generated

Arguments
Name Type Description
ttl [Number

The requested ttl

err String or Error

The error string or object

token AccessToken

The generated access token object

User.login(credentials, callback)

Login a user by with the given credentials.

   User.login({username: 'foo', password: 'bar'}, function (err, token) {
     console.log(token.id);
   });
Arguments
Name Type Description
credentials Object
callback Function
callback
Name Type Description
err Error
token AccessToken

User.logout(accessTokenID, callback)

Logout a user with the given accessToken id.

   User.logout('asd0a9f8dsj9s0s3223mk', function (err) {
     console.log(err || 'Logged out');
   });
Arguments
Name Type Description
accessTokenID String
callback Function
callback
Name Type Description
err Error

user.hasPassword(password)

Compare the given password with the users hashed password.

Arguments
Name Type Description
password String

The plain text password

Returns
Name Type Description
result Boolean

user.verify(options)

Verify a user's identity by sending them a confirmation email.

   var options = {
     type: 'email',
     to: user.email,
     template: 'verify.ejs',
     redirect: '/'
   };

   user.verify(options, next);
Arguments
Name Type Description
options Object

User.confirm(userId, token, redirect, callback)

Confirm the user's identity.

Arguments
Name Type Description
userId Any
token String

The validation token

redirect String

URL to redirect the user to once confirmed

callback Function
callback
Name Type Description
err Error

User.resetPassword(options, callback)

Create a short lived acess token for temporary login. Allows users to change passwords if forgotten.

Arguments
Name Type Description
options Object
callback Function
options
Name Type Description
email String

The user's email address

callback
Name Type Description
err Error

PersistedModel

Module Dependencies.

properties

Properties

options

Options

change = new Change

Change list entry.

Change.rectifyModelChanges(modelName, modelIds, callback)

Track the recent change of the given modelIds.

Arguments
Name Type Description
modelName String
modelIds Array
callback Function
callback
Name Type Description
err Error
changes Array

Changes that were tracked

Change.idForModel(modelName, modelId)

Get an identifier for a given model.

Arguments
Name Type Description
modelName String
modelId String

Change.findOrCreateChange(modelName, modelId, callback)

Find or create a change for the given model.

Arguments
Name Type Description
modelName String
modelId String
callback Function
callback
Name Type Description
err Error
change Change

change.rectify(callback)

Update (or create) the change with the current revision.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
change Change

change.currentRevision(callback)

Get a change's current revision based on current data.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
rev String

The current revision

Change.hash(str)

Create a hash of the given string with the options.hashAlgorithm. Default: sha1

Arguments
Name Type Description
str String

The string to be hashed

Change.revisionForInst(inst)

Get the revision string for the given object

Arguments
Name Type Description
inst Object

The data to get the revision string for

change.type()

Get a change's type. Returns one of:

  • Change.UPDATE
  • Change.CREATE
  • Change.DELETE
  • Change.UNKNOWN

change.equals(change)

Compare two changes.

Arguments
Name Type Description
change Change

change.conflictsWith(change)

Does this change conflict with the given change.

Arguments
Name Type Description
change Change

Change.bothDeleted(a, b)

Are both changes deletes?

Arguments
Name Type Description
a Change
b Change

change.isBasedOn(change)

Determine if the change is based on the given change.

Arguments
Name Type Description
change Change

Change.diff(modelName, since, remoteChanges, callback)

Determine the differences for a given model since a given checkpoint.

The callback will contain an error or result.

result

{
  deltas: Array,
  conflicts: Array
}

deltas

An array of changes that differ from remoteChanges.

conflicts

An array of changes that conflict with remoteChanges.

Arguments
Name Type Description
modelName String
since Number

Compare changes after this checkpoint

remoteChanges Change[]

A set of changes to compare

callback Function
callback
Name Type Description
err Error
result Object

See above.

Change.rectifyAll(callback)

Correct all change list entries.

Arguments
Name Type Description
callback Function

Change.getCheckpointModel()

Get the checkpoint model.

change.getModelCtor()

Get the Model class for change.modelName.

Conflict(modelId, SourceModel, TargetModel)

When two changes conflict a conflict is created.

**Note: call conflict.fetch() to get the target and source models.

Arguments
Name Type Description
modelId Any
SourceModel PersistedModel
TargetModel PersistedModel

conflict.models(callback)

Fetch the conflicting models.

Arguments
Name Type Description
callback Function
callback
Name Type Description
Error
source PersistedModel
target PersistedModel

conflict.changes(callback)

Get the conflicting changes.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
sourceChange Change
targetChange Change

conflict.resolve(callback)

Resolve the conflict.

Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error

conflict.type(callback)

Determine the conflict type.

// possible results are
Change.UPDATE // => source and target models were updated
Change.DELETE // => the source and or target model was deleted
Change.UNKNOWN // => the conflict type is uknown or due to an error
Arguments
Name Type Description
callback Function
callback
Name Type Description
err Error
type String

The conflict type.