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);
Initialize an application from an options object or a set of JSON and JavaScript files.
This function takes an optional argument that is either a string or an object.
If the argument is a string, then it sets the application root directory based on the string value. Then it:
datasources.json
file in the application root directory.models.json
file in the application root directory.If the argument is an object, then it looks for model
, dataSources
, and appRootDir
properties of the object.
If the object has no appRootDir
property then it sets the current working directory as the application root directory.
Then it:
options.dataSources
object.options.models
object.In both cases, the function loads JavaScript files in the /models
and /boot
subdirectories of the application root directory with require()
.
NOTE: mixing app.boot()
and app.model(name, config)
in multiple
files may result in models being undefined due to race conditions.
To avoid this when using app.boot()
make sure all models are passed as part of the models
definition.
Throws an error if the config object is not valid or if boot fails.
The following is example JSON for two Model
definitions: "dealership" and "location".
{
"dealership": {
// a reference, by name, to a dataSource definition
"dataSource": "my-db",
// the options passed to Model.extend(name, properties, options)
"options": {
"relations": {
"cars": {
"type": "hasMany",
"model": "Car",
"foreignKey": "dealerId"
}
}
},
// the properties passed to Model.extend(name, properties, options)
"properties": {
"id": {"id": true},
"name": "String",
"zip": "Number",
"address": "String"
}
},
"car": {
"dataSource": "my-db"
"properties": {
"id": {
"type": "String",
"required": true,
"id": true
},
"make": {
"type": "String",
"required": true
},
"model": {
"type": "String",
"required": true
}
}
}
}
Name | Type | Description |
---|---|---|
options |
String or Object
|
Boot options; If String, this is the application root directory; if object, has below properties. |
Name | Type | Description |
---|---|---|
appRootDir |
String
|
Directory to use when loading JSON and JavaScript files (optional). Defaults to the current directory ( |
models |
Object
|
Object containing |
dataSources |
Object
|
Object containing |
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.
Name | Type | Description |
---|---|---|
name |
String
|
Name of the connector, e.g. 'mysql'. |
connector |
Object
|
Connector object as returned by |
Define a DataSource.
Name | Type | Description |
---|---|---|
name |
String
|
The data source name |
config |
Object
|
The data source config |
Enable swagger REST API documentation.
Note: This method is deprecated. Use loopback-explorer instead.
Options
basePath
The basepath for your API - eg. 'http://localhost:3000'.Example
// enable docs
app.docs({basePath: 'http://localhost:3000'});
Run your app then navigate to the API explorer. Enter your API basepath to view your generated docs.
Enable app wide authentication.
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.
Name | Type | Description |
---|---|---|
cb |
Function
|
If specified, the callback is added as a listener for the server's "listening" event. |
Name | Type | Description |
---|---|---|
result |
http.Server
|
A node |
Define and attach a model to the app. The Model
will be available on the
app.models
object.
var Widget = app.model('Widget', {dataSource: 'db'});
Widget.create({name: 'pencil'});
app.models.Widget.find(function(err, widgets) {
console.log(widgets[0]); // => {name: 'pencil'}
});
Name | Type | Description |
---|---|---|
modelName |
String
|
The name of the model to define. |
config |
Object
|
The model's configuration. |
Name | Type | Description |
---|---|---|
dataSource |
String or DataSource
|
The |
[options] |
Object
|
an object containing |
[options.acls] |
Array.<ACL>
|
an array of |
[options.hidden] |
Array.<String>
|
experimental an array of properties to hide when accessed remotely. |
[properties] |
Object
|
object defining the |
Name | Type | Description |
---|---|---|
result |
ModelConstructor
|
the model class |
Get the models exported by the app. Returns only models defined using app.model()
There are two ways to access models:
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;
Name | Type | Description |
---|---|---|
result |
Array
|
Array of model classes. |
Get all remote objects.
Name | Type | Description |
---|---|---|
result |
Object
|
Lazily load a set of remote objects.
NOTE: Calling app.remotes()
more than once returns only a single set of remote objects.
Name | Type | Description |
---|---|---|
result |
RemoteObjects
|
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();
Attach any model that does not have a dataSource to the default dataSource for the type the Model requests
Create a data source with passing the provided options to the connector.
Name | Type | Description |
---|---|---|
name |
String
|
Optional name. |
Data |
Object
|
Source options |
Name | Type | Description |
---|---|---|
connector |
Object
|
LoopBack connector. |
Other properties |
|
See the relevant connector documentation. |
Create a named vanilla JavaScript class constructor with an attached set of properties and options.
Name | Type | Description |
---|---|---|
name |
String
|
Unique name. |
properties |
Object
|
|
options |
Object
|
(optional) |
Get the default dataSource
for a given type
.
Name | Type | Description |
---|---|---|
type |
String
|
The datasource type |
Name | Type | Description |
---|---|---|
result |
DataSource
|
The data source instance |
Look up a model class by name from all models created by loopback.createModel()
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Model
|
The model class |
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.
Name | Type | Description |
---|---|---|
The |
Model
|
base model class |
Name | Type | Description |
---|---|---|
result |
Model
|
The subclass if found or the base class |
Get an in-memory data source. Use one if it already exists.
Name | Type | Description |
---|---|---|
[name] |
String
|
The name of the data source. If not provided, the |
Add a remote method to a model.
Name | Type | Description |
---|---|---|
fn |
Function
|
|
options |
Object
|
(optional) |
Set the default dataSource
for a given type
.
Name | Type | Description |
---|---|---|
type |
String
|
The datasource type |
dataSource |
Object or DataSource
|
The data source settings or instance |
Name | Type | Description |
---|---|---|
result |
DataSource
|
The data source instance |
Create a template helper.
var render = loopback.template('foo.ejs');
var html = render({foo: 'bar'});
Name | Type | Description |
---|---|---|
path |
String
|
Path to the template file. |
Name | Type | Description |
---|---|---|
result |
Function
|
The built in loopback.Model.
Name | Type | Description |
---|---|---|
data |
Object
|
Check if the given access token can invoke the method
Name | Type | Description |
---|---|---|
token |
AccessToken
|
The access token |
modelId |
|
The model id |
sharedMethod |
SharedMethod
|
|
callback |
|
The callback function |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object |
allowed |
Boolean
|
is the request allowed |
Get the Application
the Model is attached to.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
app |
Application
|
Get the Model's RemoteObjects
.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
remoteObjects |
RemoteObjects
|
Extends Model with basic query and CRUD support.
Change Event
Listen for model changes using the change
event.
MyDataModel.on('changed', function(obj) {
console.log(obj) // => the changed model
});
Name | Type | Description |
---|---|---|
data |
Object
|
|
data.id |
Number
|
The default id property |
Return count of matched records
Name | Type | Description |
---|---|---|
where |
Object
|
search conditions (optional) |
cb |
Function
|
callback, called with (err, count) |
Create new instance of Model class, saved in database.
Name | Type | Description |
---|---|---|
[data] |
Object
|
Object containing model instance data. |
callback |
Function
|
Callback function; see below. |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object |
Model |
Model
|
instance |
Check whether a model instance exists in database.
Name | Type | Description |
---|---|---|
id |
id
|
identifier of object (primary key value) |
cb |
Function
|
callbacl called with (err, exists: Bool) |
Find all instances of Model, matched by query
make sure you have marked as index: true
fields for filter or sort
Name | Type | Description |
---|---|---|
params |
Object
|
(optional)
|
callback |
Function
|
(required) called with arguments:
|
Find object by id
Name | Type | Description |
---|---|---|
id |
|
primary key value |
cb |
Function
|
callback called with (err, instance) |
Find one record, same as all
, limited by 1 and return object, not collection
Name | Type | Description |
---|---|---|
params |
Object
|
search conditions: {where: {test: 'me'}} |
cb |
Function
|
callback called with (err, instance) |
Find one record instance, same as all
, limited by one and return object, not collection.
If not found, create the record using data provided as second argument.
Name | Type | Description |
---|---|---|
query |
Object
|
search conditions: {where: {test: 'me'}}. |
data |
Object
|
object to create. |
cb |
Function
|
callback called with (err, instance) |
Get the id property name
Destroy all matching records
Name | Type | Description |
---|---|---|
[where] |
Object
|
An object that defines the criteria |
[cb] |
Function
|
callback called with (err) |
Destroy a record by id
Name | Type | Description |
---|---|---|
id |
|
The id value |
cb |
Function
|
callback called with (err) |
Update or insert a model instance
Name | Type | Description |
---|---|---|
data |
Object
|
The model instance data |
[callback] |
Function
|
The callback function |
Get the id property name of the constructor.
Determine if the data model is new.
Name | Type | Description |
---|---|---|
result |
Boolean
|
True if data model is new. |
Reload object from persistence
Name | Type | Description |
---|---|---|
callback |
Function
|
Callback function |
Name | Type | Description |
---|---|---|
err |
Error
|
|
instance |
Object
|
Save instance. When instance does not have an ID, create method instead. Triggers: validate, save, update or create.
Name | Type | Description |
---|---|---|
Options |
[options]
|
|
callback |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
validate |
Boolean
|
Whether to validate. |
throws |
Boolean
|
Name | Type | Description |
---|---|---|
err |
Error
|
Error object |
Object
|
Set the corret id
property for the DataModel
. 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.
Name | Type | Description |
---|---|---|
val |
|
The |
Update single attribute.
Equivalent to updateAttributes({name: value}, cb)
Name | Type | Description |
---|---|---|
name |
String
|
name of property |
value |
Mixed
|
value of property |
callback |
Function
|
callback called with (err, instance) |
Update set of attributes
Performs validation before updating
Name | Type | Description |
---|---|---|
data |
Object
|
data to update |
callback |
Function
|
callback called with (err, instance) |
Expose models over REST.
For example:
app.use(loopback.rest());
For more information, see Exposing models over a REST API.
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
}
Check for an access token in cookies, headers, and query string parameters. This function always checks for the following:
access_token
X-Access-Token
authorization
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']
}));
Name | Type | Description |
---|---|---|
[options] |
Object
|
Each option array is used to add additional keys to find an |
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. |
Convert any request not handled so far to a 404 error to be handled by error-handling middleware.
Token based authentication and access control.
Name | Type | Description |
---|---|---|
id |
|
{String} Generated token ID |
ttl |
|
{Number} Time to live |
created |
|
{Date} When the token was created Default ACLs
|
Create a cryptographically random access token id.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
token |
String
|
Find a token for the given ServerRequest
.
Name | Type | Description |
---|---|---|
req |
ServerRequest
|
|
[options] |
Object
|
Options for finding the token |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
token |
AccessToken
|
Validate the token.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
isValid |
Boolean
|
Name of the access type - READ/WRITE/EXEC
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.
Type of the principal - Application/User/Role
Id of the principal - such as appId, userId or roleId
A Model for access control meta data.
Check if the request has the permission to access
Name | Type | Description |
---|---|---|
context |
Object
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
principals |
Array.<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 |
Check if the given access token can invoke the method
Name | Type | Description |
---|---|---|
token |
AccessToken
|
The access token |
model |
String
|
The model name |
modelId |
|
The model id |
method |
String
|
The method name |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object |
allowed |
Boolean
|
is the request allowed |
Check if the given principal is allowed to access the model/property
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
|
The callback function |
callback
|
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object |
result |
AccessRequest
|
The access permission |
Calculate the matching score for the given rule and request
Name | Type | Description |
---|---|---|
rule |
ACL
|
The ACL entry |
req |
AccessRequest
|
The request |
Name | Type | Description |
---|---|---|
result |
number
|
Get matching score for the given AccessRequest
.
Name | Type | Description |
---|---|---|
req |
AccessRequest
|
The request |
Name | Type | Description |
---|---|---|
result |
Number
|
score |
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
Check if the given scope is allowed to access the model/property
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
|
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object |
result |
AccessRequest
|
The access permission |
production or development mode. It denotes what default APNS servers to be used to send notifications
Manage client applications and organize their users.
Authenticate the application id and key.
matched
parameter is one of:
Name | Type | Description |
---|---|---|
appId |
Any
|
|
key |
String
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
matched |
String
|
The matching key |
Register a new application
Name | Type | Description |
---|---|---|
owner |
|
Owner's user id |
name |
|
Name of the application |
options |
|
Other options |
cb |
|
Callback function |
Reset keys for a given application by the appId
Name | Type | Description |
---|---|---|
appId |
Any
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Reset keys for the application instance
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
The Email Model.
Properties
to
- String (required)from
- String (required)subject
- String (required)text
- Stringhtml
- StringSend an email with the given options
.
Example Options:
{
from: "Fred Foo <foo@blurdybloop.com>", // sender address
to: "bar@blurdybloop.com, baz@blurdybloop.com", // 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.
Name | Type | Description |
---|---|---|
options |
Object
|
See below |
callback |
Function
|
Called after the e-mail is sent or the sending failed |
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) |
The Role Model
List roles for a given principal
Name | Type | Description |
---|---|---|
context |
Object
|
The security context |
callback |
Function
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
|
|
An |
Array.<String>
|
array of role ids |
Check if the user id is authenticated
Name | Type | Description |
---|---|---|
context |
Object
|
The security context |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
isAuthenticated |
Boolean
|
Check if a given principal is in the role
Name | Type | Description |
---|---|---|
role |
String
|
The role name |
context |
Object
|
The context object |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
isInRole |
Boolean
|
Check if a given userId is the owner the model instance
Name | Type | Description |
---|---|---|
modelClass |
Function
|
The model class |
modelId |
|
The model id |
{*) userId The user id |
|
|
callback |
Function
|
Add custom handler for roles
Name | Type | Description |
---|---|---|
role |
|
|
resolver |
|
The resolver function decides if a principal is in the role dynamically function(role, context, callback) |
The RoleMapping
model extends from the built in loopback.Model
type.
Get the application principal
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
application |
Application
|
Get the child role principal
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
childUser |
User
|
Get the user principal
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
user |
User
|
factors: [ 'AuthenticationFactor' ],
Extends from the built in loopback.Model
type.
Default User
ACLs.
*
create
removeById
login
logout
findById
updateAttributes
Confirm the user's identity.
Name | Type | Description |
---|---|---|
userId |
Any
|
|
token |
String
|
The validation token |
redirect |
String
|
URL to redirect the user to once confirmed |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Login a user by with the given credentials
.
User.login({username: 'foo', password: 'bar'}, function (err, token) {
console.log(token.id);
});
Name | Type | Description |
---|---|---|
credentials |
Object
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
token |
AccessToken
|
Logout a user with the given accessToken id.
User.logout('asd0a9f8dsj9s0s3223mk', function (err) {
console.log(err || 'Logged out');
});
Name | Type | Description |
---|---|---|
accessTokenID |
String
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Create a short lived acess token for temporary login. Allows users to change passwords if forgotten.
Name | Type | Description |
---|---|---|
options |
Object
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
String
|
The user's email address |
Name | Type | Description |
---|---|---|
err |
Error
|
Create access token for the logged in user. This method can be overridden to customize how access tokens are generated
Name | Type | Description |
---|---|---|
[Number} ttl The requested ttl |
|
|
err |
String or Error
|
The error string or object |
token |
AccessToken
|
The generated access token object |
Compare the given password
with the users hashed password.
Name | Type | Description |
---|---|---|
password |
String
|
The plain text password |
Name | Type | Description |
---|---|---|
result |
Boolean
|
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);
Name | Type | Description |
---|---|---|
options |
Object
|