var app = loopback()

LoopBackApplication

The App object represents a Loopback application.

The App object extends Express and supports Express 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.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.dataSource(name, config)

Define a DataSource.

Arguments
Name Type Description
name String

The data source name

config Object

The data source config

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

For example, to listen on host/port configured in app config:

app.listen();

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

For example, to listen on the specified port and all hosts, and 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.

app.model(Model, config)

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

Example - Attach an existing model:

var User = loopback.User;
app.model(User);

Example - Attach an existing model, alter some aspects of the model:

var User = loopback.User;
app.model(User, { dataSource: 'db' });
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
});
  1. 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.remoteObjects()

Get all remote objects.

Returns
Name Type Description
result Object

Remote objects.

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

loopback

loopback

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();
Class Properties
Name Type Description
version String

Version of LoopBack framework. Static read-only property.

mime String
isBrowser Boolean

True if running in a browser environment; false otherwise. Static read-only property.

isServer Boolean

True if running in a server environment; false otherwise. Static read-only property.

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.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([name])

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(type)

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(data)

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. Argument: inst, model instance, object

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. Argument: id, model ID (number).

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

Event: deletedAll

Emitted after an individual model has been deleted. Argument: where (optional), where filter, JSON object.

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.

Event: set

Emitted when model property is set. Argument: inst, model instance, object

MyModel.on('set', function(inst) {
  console.log('model with id %s has been changed', inst.id);
  // => model with id 1 has been changed
});
Arguments
Name Type Description
data Object
Class Properties
Name Type Description
modelName String

The name of the model. Static property.

dataSource DataSource

Data source to which the model is connected, if any. Static property.

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

Check if the given access token can invoke the specified method.

Arguments
Name Type Description
token AccessToken

The access token.

modelId Any

The model ID.

sharedMethod SharedMethod

The method in question.

ctx Object

The remote invocation context.

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.disableRemoteMethod(name, isStatic)

Disable remote invocation for the method with the given name.

Arguments
Name Type Description
name String

The name of the method.

isStatic Boolean

Is the method static (eg. MyModel.myMethod)? Pass false if the method defined on the prototype (eg. MyModel.prototype.myMethod).

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. See Defining remote methods for more information.

Static method example:

Model.myMethod();
Model.remoteMethod('myMethod');
Arguments
Name Type Description
name String

The name of the method.

options Object

The remoting options.

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

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.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.count([filter], cb)

Return the number of records that match the optional filter.

Arguments
Name Type Description
[filter] Object

Optional where filter JSON object; see below.

cb Function

Callback function called with (err, count).

[filter]
Name Type Description
where Object

Where clause, like { key: val, key2: {gt: 'val2'}, ...}

PersistedModel.create(data, cb)

Create new instance of Model class, saved in database

Arguments
Name Type Description
data Object

Optional data object.

cb Function

Callback function with cb(err, obj) signature, where err is error object and obj is null or Model instance.

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.currentCheckpoint(callback)

Get the current checkpoint id.

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

persistedModel.destroy(callback)

Deletes the model from persistence. Triggers destroy hook (async) before and after destroying object.

Arguments
Name Type Description
callback Function

Callback function.

PersistedModel.destroyAll([where], [cb])

Destroy all model instances that match the optional filter specification.

Arguments
Name Type Description
[where] Object

Optional where filter JSON object; see below.

[cb] Function

callback called with (err).

[where]
Name Type Description
where Object

Where clause, like { key: val, key2: {gt: 'val2'}, ...}

PersistedModel.destroyById(id, cb)

Destroy model instance with the specified ID.

Arguments
Name Type Description
id Any

The ID value of model instance to delete.

cb Function

Callback function called with (err).

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

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

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

Callback function called with (err, exists: Bool)

PersistedModel.find([filter], Callback)

Find all model instances that match filter specification. See Querying models.

Arguments
Name Type Description
[filter] Object

Optional Filter JSON object; see below.

Callback Function

function called with (err, returned-instances).

[filter]
Name Type Description
fields String or Object or Array

Identify fields to include in return result.
See Fields filter.

include String or Object or Array

See PersistedModel.include documentation.
See Include filter.

limit Number

Maximum number of instances to return.
See Limit filter.

order String

Sort order: either "ASC" for ascending or "DESC" for descending.
See Order filter.

skip Number

Number of results to skip.
See Skip filter.

where Object

Where clause, like { key: val, key2: {gt: 'val2'}, ...}
See Where filter.

Returns
Name Type Description
result Object

Array of model instances that match the filter; or Error.

PersistedModel.findById(id, cb)

Find object by ID.

Arguments
Name Type Description
id Any

primary key value

cb Function

Callback function called with (err, instances). Required.

PersistedModel.findOne([filter], Callback)

Find one model instance that matches filter specification. Same as find, but limited to one result; Returns object, not collection.

Arguments
Name Type Description
[filter] Object

Optional Filter JSON object; see below.

Callback Function

function called with (err, returned-instance). Required.

[filter]
Name Type Description
fields String or Object or Array

Identify fields to include in return result.
See Fields filter.

include String or Object or Array

See PersistedModel.include documentation.
See Include filter.

limit Number

Maximum number of instances to return.
See Limit filter.

order String

Sort order: either "ASC" for ascending or "DESC" for descending.
See Order filter.

skip Number

Number of results to skip.
See Skip filter.

where Object

Where clause, like { key: val, key2: {gt: 'val2'}, ...}
See Where filter.

Returns
Name Type Description
result Object

First model instance that matches the filter; or Error.

PersistedModel.findOrCreate(query, data, cb)

Find one record, same as find, but limited to one object. Returns an object, not collection. If not found, create the object 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 cb(err, instance) signature.

PersistedModel.getChangeModel()

Get the Change model.

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

Determine if the data model is new.

Returns
Name Type Description
result Boolean

Returns true if the data model is new; false otherwise.

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

persistedModel.reload(callback)

Reload object from persistence. Requires id member of object to be able to call find.

Arguments
Name Type Description
callback Function

Callback function called with (err, instance) arguments.

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.save([options], [callback])

Save model instance. If the instance doesn't have an ID, then the create method is called instead. Triggers: validate, save, update, or create.

Arguments
Name Type Description
[options] Object

See below.

[callback] Function

Callback function called with (err, obj).

[options]
Name Type Description
validate Boolean
throws Boolean

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. Override this method to handle complex IDs.

Arguments
Name Type Description
val Any

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

PersistedModel.updateAll([where], data, cb)

Update multiple instances that match the where clause

Example:

Employee.update({managerId: 'x001'}, {managerId: 'x002'}, function(err) {
    ...
});
Arguments
Name Type Description
[where] Object

Optional where filter JSON object; see below.

data Object

Changes to be made

cb Function

Callback function called with (err, count).

[where]
Name Type Description
where Object

Where clause, like { key: val, key2: {gt: 'val2'}, ...}

persistedModel.updateAttribute(name, value, callback)

Update a single attribute. Equivalent to updateAttributes({name: 'value'}, cb)

Arguments
Name Type Description
name String

Name of property

value Mixed

Value of property

callback Function

Callback function called with (err, instance).

persistedModel.updateAttributes(data, callback)

Update set of attributes. Performs validation before updating.

Trigger: validation, save and update hooks

Arguments
Name Type Description
data Object

Dta to update.

callback Function

Callback function called with (err, instance).

PersistedModel.upsert(data, [callback])

Update or insert a model instance

Arguments
Name Type Description
data Object

The model instance data

[callback] Function

The callback function

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

AccessToken

Token based authentication and access control.

Default ACLs

  • DENY EVERYONE *
  • ALLOW EVERYONE create
Class Properties
Name Type Description
id String

Generated token ID

ttl Number

Time to live in seconds, 2 weeks by default.

created Date

When the token was created

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

ACL

ACL

A Model for access control meta data.

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?

Class Properties
Name Type Description
model String

Name of the model.

property String

Name of the property, method, scope, or relation.

accessType String

Type of access being granted: one of READ, WRITE, or EXECUTE.

permission String

Type of permission granted. One of: - ALARM: Generate an alarm, in a system-dependent way, the access specified in the permissions component of the ACL entry.

  • ALLOW: Explicitly grants access to the resource.
  • AUDIT: Log, in a system-dependent way, the access specified in the permissions component of the ACL entry.
  • DENY: Explicitly denies access to the resource.
principalType String

Type of the principal; one of: Application, Use, Role.

principalId String

ID of the principal - such as appId, userId or roleId

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

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

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

scope = new Scope

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

Application

Manage client applications and organize their users.

Class Properties
Name Type Description
id String

Generated ID.

name String

Name; required.

description String

Text description

icon String

String Icon image URL.

owner String

User ID of the developer who registers the application.

email String

E-mail address

emailVerified Boolean

Whether the e-mail is verified.

url String

OAuth 2.0 application URL.

callbackUrls String[]

The OAuth 2.0 code/token callback URL.

status String

Status of the application; Either production, sandbox (default), or disabled.

created Date

Date Application object was created. Default: current date.

modified Date

Date Application object was modified. Default: current date.

pushSettings.apns Object

APNS configuration, see the options below and also https://github.com/argon/node-apn/blob/master/doc/apn.markdown

pushSettings.apns.production Boolean

Whether to use production Apple Push Notification Service (APNS) servers to send push notifications. If true, uses gateway.push.apple.com:2195 and feedback.push.apple.com:2196. If false, uses gateway.sandbox.push.apple.com:2195 and feedback.sandbox.push.apple.com:2196

pushSettings.apns.certData String

The certificate data loaded from the cert.pem file (APNS).

pushSettings.apns.keyData String

The key data loaded from the key.pem file (APNS).

pushSettings.apns.pushOptions.gateway String

(APNS).

pushSettings.apns.pushOptions.port Number

(APNS).

pushSettings.apns.feedbackOptions.gateway String

(APNS).

pushSettings.apns.feedbackOptions.port Number

(APNS).

pushSettings.apns.feedbackOptions.batchFeedback Boolean

(APNS).

pushSettings.apns.feedbackOptions.interval Number

(APNS).

pushSettings.gcm.serverApiKey: String

Google Cloud Messaging API key.

authenticationEnabled Boolean
anonymousAllowed Boolean
authenticationSchemes Array

List of authentication schemes (see below).

authenticationSchemes.scheme String

Scheme name. Supported values: local, facebook, google, twitter, linkedin, github.

authenticationSchemes.credential Object

Scheme-specific credentials.

Application.authenticate(appId, key, callback)

Authenticate the application id and key.

Arguments
Name Type Description
appId Any
key String
callback Function
callback
Name Type Description
err Error
matched String

The matching key; one of: - clientKey

  • javaScriptKey
  • restApiKey
  • windowsKey
  • masterKey

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

email = new Email

Email

Email model. Extends LoopBack base Model.

Class Properties
Name Type Description
to String

Email addressee. Required.

from String

Email sender address. Required.

subject String

Email subject string. Required.

text String

Text body of email.

html String

HTML body of email.

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)

email.send()

A shortcut for Email.send(this).

roleMapping = new RoleMapping

RoleMapping

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

Class Properties
Name Type Description
id String

Generated ID.

name String

Name of the role.

Description String

Text description.

roleMapping.application(callback)

Get the application principal

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

roleMapping.childRole(callback)

Get the child role principal

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

roleMapping.user(callback)

Get the user principal

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

role = new Role

Role

The Role Model

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

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.isOwner(modelClass, modelId, userId, callback)

Check if a given user ID is the owner the model instance.

Arguments
Name Type Description
modelClass Function

The model class

modelId Any

The model ID

userId Any

The user ID

callback Function

Callback function

Role.registerResolver(role, resolver)

Add custom handler for roles.

Arguments
Name Type Description
role String

Name of role.

resolver Function

Function that determines if a principal is in the specified role. Signature must be function(role, context, callback)

user = new User

User

Built-in User model. Extends LoopBack PersistedModel.

Default User ACLs.

  • DENY EVERYONE *
  • ALLOW EVERYONE create
  • ALLOW OWNER deleteById
  • ALLOW EVERYONE login
  • ALLOW EVERYONE logout
  • ALLOW EVERYONE findById
  • ALLOW OWNER updateAttributes
Class Properties
Name Type Description
username String

Must be unique

password String

Hidden from remote clients

email String

Must be valid email

emailVerified Boolean

Set when a user's email has been verified via confirm()

verificationToken String

Set when verify() is called

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.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.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.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.normalizeCredentials(credentials, realmRequired, realmDelimiter)

Normalize the credentials

Arguments
Name Type Description
credentials Object

The credential object

realmRequired Boolean
realmDelimiter String

The realm delimiter, if not set, no realm is needed

Returns
Name Type Description
result Object

The normalized credential object

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

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
options
Name Type Description
type String

Must be 'email'.

to String

Email address to which verification email is sent.

from String

Sender email addresss, for example '[email protected]'.

subject String

Subject line text.

text String

Text of email.

template String

Name of template that displays verification page, for example, `'verify.ejs'.

redirect String

Page to which user will be redirected after they verify their email, for example '/' for root URI.

change = new Change

Change

Change list entry.

Class Properties
Name Type Description
id String

Hash of the modelName and id

rev String

The current model revision

prev String

The previous model revision

checkpoint Number

The current checkpoint at time of the change

modelName String

Model name

modelId String

Model ID

Change.bothDeleted(a, b)

Are both changes deletes?

Arguments
Name Type Description
a Change
b Change

change.conflictsWith(change)

Does this change conflict with the given change.

Arguments
Name Type Description
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.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.equals(change)

Compare two changes.

Arguments
Name Type Description
change Change

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

Get the checkpoint model.

change.getModelCtor()

Get the Model class for change.modelName.

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.idForModel(modelName, modelId)

Get an identifier for a given model.

Arguments
Name Type Description
modelName String
modelId String

change.isBasedOn(change)

Determine if the change is based on the given change.

Arguments
Name Type Description
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.rectifyAll(callback)

Correct all change list entries.

Arguments
Name Type Description
callback Function

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.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.Conflict = new Change.Conflict

Change.Conflict

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
Class Properties
Name Type Description
source ModelClass

The source model instance

target ModelClass

The target model instance

conflict.changes(callback)

Get the conflicting changes.

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

conflict.models(callback)

Fetch the conflicting models.

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

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