LoopBack

LoopBack is a mobile backend framework that you can run in the cloud or on-premises.
It is built on StrongNode and open-source Node.js modules. For more information on the advantages of using LoopBack, see StrongLoop | LoopBack.

To gain a basic understanding of key LoopBack concepts, read the following Overview section. Then, dive right into creating an app in Quick Start.

Overview

LoopBack consists of:

A library of Node.js modules for connecting mobile apps to data sources such as databases and REST APIs.

A command line tool, slc lb, for creating and working with LoopBack applications.

Client SDKs for native and web-based mobile clients.

As illustrated in the diagram below, a LoopBack application has three components:

Models that represent business data and behavior.

Data sources and connectors. Data sources are databases or other backend services such as REST APIs, SOAP web services, or storage services. Connectors provide apps access to enterprise data sources such as Oracle, MySQL, and MongoDB.

Mobile clients can call LoopBack server APIs directly using Strong Remoting, a pluggable transport
layer that enables you to provide backend APIs over REST, WebSockets, and other transports.

##Quick Start

This section will get you up and running with LoopBack and the StrongLoop sample app in just a few minutes.

Prerequisites

You must have the git command-line tool installed to run the sample application.
If needed, download it at http://git-scm.com/downloads and install it.

On Linux systems, you must have root privileges to write to /usr/share.

NOTE: If you're using Windows or OSX and don't have a C compiler (Visual C++ on Windows or XCode on OSX) and command-line "make" tools installed, you will see errors such as these:

xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>,
or see the xcode-select manpage (man xcode-select) for further information.
...
Unable to load native module uvmon; some features may be unavailable without compiling it.
memwatch must be installed to use the instances feature
StrongOps not configured to monitor. Please refer to http://docs.strongloop.com/strong-agent for usage.

You will still be able to run the sample app, but StrongOps will not be able to collect certain statistics.

Creating and Running the Sample App

Follow these steps to run the LoopBack sample app:

If you have not already done so, download and install StrongLoop Suite or set up your cloud development platform.

Setup the StrongLoop Suite sample app with this command.

$ slc example

This command clones the sample app into a new directory
named sls-sample-app and installs all of its dependencies.

Run the sample application by entering this command:

$ cd sls-sample-app
$ slc run app

To see the app running in a browser, open http://localhost:3000. The app homepage lists sample requests you can make against the LoopBack REST API. Click the GET buttons to see the JSON data returned.

About the sample app

The StrongLoop sample is a mobile app for "Blackpool," an imaginary military equipment rental dealer with outlets in major cities around the world. It enables customers (military commanders) to rent weapons and buy ammunition from Blackpool using their mobile phones. The app displays a map of nearby rental locations and see currently available weapons, which you can filter by price, ammo type and distance. Then, you can use the app to reserve the desired weapons and ammo.

Note that the sample app is the backend functionality only; that is, the app has a REST API, but no client app or UI to consume the interface.

Using the API Explorer

Follow these steps to explore the sample app's REST API:

Open your browser to http://localhost:3000/explorer. You'll see a list of REST API endpoints as illustrated below.
The endpoints are grouped by the model names. Each endpoint consists of a list
of operations for the model.

Click on one of the endpoint paths (such as /locations) to see available
operations for a given model. You'll see the CRUD operations mapped to HTTP verbs and paths.

Click on a given operation to see the signature; for example, GET /locations/{id}:
Notice that each operation has the HTTP verb, path, description, response model, and a list of request parameters.

Invoke an operation: fill in the parameters, then click the Try it out! button. You'll see something like this:

You can see the request URL, the JSON in the response body, and the HTTP response code and headers.

Working with Models

A LoopBack model consists of:

Application data.

Validation rules.

Data access capabilities.

Business logic.

Apps use the model API to display information to the user or trigger actions
on the models to interact with backend systems. LoopBack supports both "dynamic" schema-less models and "static", schema-driven models.

Dynamic models require only a name. The format of the data are specified completely and flexibly by the client application. Well-suited for data that originates on the client, dynamic models enable you to persist data both between accessTokens and between devices without involving a schema.

Static models require more code up front, with the format of the data specified completely in JSON. Well-suited to both existing data and large, intricate datasets, static models provide structure and
consistency to their data, preventing bugs that can result from unexpected data in the database.

Here is a simple example of creating and using a model.

Defining a Model

Consider an e-commerce app with Product and Inventory models.
A mobile client could use the Product model API to search through all of the
products in a database. A client could join the Product and Inventory data to
determine what products are in stock, or the Product model could provide a
server-side function (or remote method) that aggregates this
information.

The above code creates two dynamic models, appropriate when data is "free form." However, some data sources, such as relational databases, require schemas. Additionally, schemas are valuable to enable data exchange and to validate or sanitize data from clients; see Sanitizing and Validating Models.

Attaching a Model to a Data Source

A data source enables a model to access and modify data in backend system such as a relational database.
Attaching a model to a data source, enables the model to use the data source API. For example, as shown below, the MongoDB Connector, mixes in a create method that you can use to store a new product in the database; for example:

After this, you'll have the Product model with create, read, update, and delete (CRUD) functions working remotely
from mobile clients. At this point, the model is schema-less and the data are not checked.

Sanitizing and Validating Models

A schema provides a description of a model written in LoopBack Definition Language, a specific form of JSON. Once a schema is defined for a model, the model validates and sanitizes data before passing it on to a data store such as a database. A model with a schema is referred to as a static model.

For example, the following code defines a schema and assigns it to the product model. The schema defines two fields (columns): name, a string, and price, a number. The field name is a required value.

A schema imposes restrictions on the model: If a remote client tries to save a product with extra properties
(for example, description), those properties are removed before the app saves the data in the model.
Also, since name is a required value, the model will only be saved if the product contains a value for the name property.

Models access data sources through connectors that are extensible and customizable.Connectors implement the data exchange logic using database drivers or other
client APIs. In general, application code does not use a connector directly.
Rather, the DataSource class provides an API to configure the underlying connector.

Defining a model with loopback.createModel() is really just extending the base loopback.Model type using loopback.Model.extend(). The bundled models extend from the base loopback.Model allowing you to extend them arbitrarily.

User Model

Register and authenticate users of your app locally or against 3rd party services.

Login a User

You must provide a username and password over rest. To ensure these values are encrypted, include these as part of the body and make sure you are serving your app over https (through a proxy or using the https node server).

Verify Email Addresses

Require a user to verify their email address before being able to login. This will send an email to the user containing a link to verify their address. Once the user follows the link they will be redirected to / and be able to login normally.

Remote Password Reset Confirmation

AccessToken Model

Identify users by creating accessTokens when they connect to your loopback app. By default the loopback.User model uses the loopback.AccessToken model to persist accessTokens. You can change this by setting the accessToken property.

Command Line Tool

StrongLoop Suite includes a command-line tool, slc (StrongLoop Command), for working with applications.
The slc lb command enables you to quickly create new LoopBack applications and models with the following sub-commands:

workspace: create a new workspace, essentially a container for multiple projects.

app.boot([options])

Initialize an application from an options object or a set of JSON and JavaScript files.

What happens during an app boot?

DataSources are created from an options.dataSources object or datasources.json in the current directory

Models are created from an options.models object or models.json in the current directory

Any JavaScript files in the ./models directory are loaded with require().

Options

cwd - optional - the directory to use when loading JSON and JavaScript files

models - optional - an object containing Model definitions

dataSources - optional - an object containing DataSource definitions

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.

Model Definitions

The following is an example of an object containing two Model definitions: "location" and "inventory".

NOTE: The loopback.token() middleware will only check for signed cookies.

Model

A Loopback Model is a vanilla JavaScript class constructor with an attached set of properties and options. A Model instance is created by passing a data object containing properties to the Model constructor. A Model constructor will clean the object passed to it and only set the values matching the properties you define.

Note: until a model is attached to a data source it will not have any attached methods.

CRUD and Query Mixins

Mixins are added by attaching a vanilla model to a data source with a connector. Each connector enables its own set of operations that are mixed into a Model as methods. To see available methods for a data source call dataSource.operations().

http.path - the path relative to the model the method will be exposed at. May be a path fragment (eg. '/:myArg') which will be populated by an arg of the same name in the accepts description. For example the stats method above will be at the whole path /products/stats.

Model.hasMany(Model, options)

Book.create(function(err, book) {
// create a chapter instance// ready to be saved in the data sourcevar chapter = book.chapters.build({name: 'Chapter 1'});
// save the new chapter
chapter.save();
// you can also call the Chapter.create method with// the `chapters` property which will build a chapter// instance and save the it in the data source
book.chapters.create({name: 'Chapter 2'}, function(err, savedChapter) {
// this callback is optional
});
// query chapters for the book using the
book.chapters(function(err, chapters) {
// all chapters with bookId = book.idconsole.log(chapters);
});
book.chapters({where: {name: 'test'}, function(err, chapters) {
// all chapters with bookId = book.id and name = 'test'console.log(chapters);
});
});

Model.belongsTo(Model, options)

A belongsTo relation sets up a one-to-one connection with another model, such
that each instance of the declaring model "belongs to" one instance of the other
model. For example, if your application includes users and posts, and each post
can be written by exactly one user.

Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});

The code above basically says Post has a reference called author to User using
the userId property of Post as the foreign key. Now we can access the author
in one of the following styles:

post.author(callback); // Get the User object for the post author asynchronously
post.author(); // Get the User object for the post author synchronously
post.author(user) // Set the author to be the given user

Model.hasAndBelongsToMany(Model, options)

A hasAndBelongsToMany relation creates a direct many-to-many connection with
another model, with no intervening model. For example, if your application
includes users and groups, with each group having many users and each user
appearing in many groups, you could declare the models this way,

User.hasAndBelongsToMany('groups', {model: Group, foreignKey: 'groupId'});
user.groups(callback); // get groups of the user
user.groups.create(data, callback); // create a new group and connect it with the user
user.groups.add(group, callback); // connect an existing group with the user
user.groups.remove(group, callback); // remove the user from the group

Shared Methods

Any static or instance method can be decorated as shared. These methods are exposed over the provided transport (eg. loopback.rest).

Include the connector in your package.json dependencies and run npm install.

{
"dependencies": {
"loopback-connector-oracle": "latest"
}
}

Memory Connector

The built-in memory connector allows you to test your application without connecting to an actual persistent data source, such as a database. Although the memory connector is very well tested it is not recommended to be used in production. Creating a data source using the memory connector is very simple.

Browser API

Stay tuned. Currently in development.

Android API

REST API

The REST API allows clients to interact with the LoopBack models using HTTP.
The clients can be a web browser, a JavaScript program, a mobile SDK, a curl
script, or anything that can act as an HTTP client.

LoopBack automatically binds a model to a list of HTTP endpoints that provide
REST APIs for model instance data manipulations (CRUD) and other remote
operations.

We'll use a simple model called Location (locations for rental) to illustrate
what REST APIs are exposed by LoopBack.

By default, the REST APIs are mounted to /<pluralFormOfTheModelName>, for
example, /locations, to the base URL such as http://localhost:3000/.

CRUD remote methods

For a model backed by a data source that supports CRUD operations, you'll see
the following endpoints:

Model.create: POST /locations

Model.upsert: PUT /locations

Model.exists: GET /locations/:id/exists

Model.findById: GET /locations/:id

Model.find: GET /locations

Model.findOne: GET /locations/findOne

Model.deleteById: DELETE /locations/:id

Model.count: GET /locations/count

Model.prototype.updateAttributes: PUT /locations/:id

Custom remote methods

To expose a JavaScript method as REST API, we can simply describe the method as
follows: