Strongloop

nodejs-frameworks

Resources

Data access and security
Datasources
Model

http://webapplog.com/loopback-101-express-js-on-steroids/
http://strongloop.com/strongblog/node-js-ruby-on-rails-getting-started/ - done reading
http://docs.strongloop.com/display/public/LB/LoopBack+core+concepts - done reading
http://docs.strongloop.com/display/public/LB/Getting+started+with+LoopBack - done reading
http://docs.strongloop.com/display/public/LB/Create+new+data+source - done reading
http://docs.strongloop.com/display/public/LB/Use+API+Explorer - done reading
http://docs.strongloop.com/display/public/LB/Learn+more - done reading
http://docs.strongloop.com/display/public/LB/Environment-specific+configuration - done reading
http://docs.strongloop.com/display/public/LB/Validating+model+data
http://docs.strongloop.com/display/public/LB/Creating+model+relations
http://docs.strongloop.com/pages/viewpage.action?pageId=3836277
http://apidocs.strongloop.com/loopback/#loopback
http://apidocs.strongloop.com/loopback/#var-app-loopback
http://apidocs.strongloop.com/loopback-boot/#boot
http://docs.strongloop.com/display/LB/Property+generator
http://docs.strongloop.com/display/LB/Swagger+generator
http://docs.strongloop.com/display/ARC/StrongLoop+Arc
http://docs.strongloop.com/display/LB/Project+layout+reference
http://docs.strongloop.com/display/LB/Environment-specific+configuration
http://docs.strongloop.com/display/LB/AngularJS+JavaScript+SDK
http://docs.strongloop.com/display/LB/Tutorials+and+examples
http://docs.strongloop.com/display/LB/Working+with+LoopBack+objects
http://docs.strongloop.com/display/LB/Defining+boot+scripts
http://docs.strongloop.com/display/LB/Data+source+generator
https://github.com/strongloop/loopback
http://docs.strongloop.com/display/LB/datasources.json
http://docs.strongloop.com/display/LB/Defining+boot+scripts
http://docs.strongloop.com/display/SLC/StrongLoop+Controller
http://docs.strongloop.com/display/SLA/Application+monitoring
http://docs.strongloop.com/display/SLC/Application+clustering
http://www.slideshare.net/rfeng/loopback-mysql
http://docs.strongloop.com/strong-agent
http://onehungrymind.com/build-simple-rest-app-angularjs-part-1-node-api-strongloop/
http://docs.strongloop.com/display/LB/Getting+Started+with+LoopBack
http://docs.strongloop.com/display/LB/AngularJS+JavaScript+SDK
http://docs.strongloop.com/pages/viewpage.action?pageId=3836205
https://github.com/strongloop/loopback-sdk-angular-cli
http://apidocs.strongloop.com/
https://groups.google.com/forum/#!forum/loopbackjs
http://loopback.io/resources/
http://docs.strongloop.com/display/LB/Data+sources+and+connectors
http://docs.strongloop.com/display/SL/StrongLoop
http://docs.strongloop.com/display/LB/LoopBack+2.0
http://docs.strongloop.com/display/LB
http://docs.strongloop.com/display/SLC/Getting+started+with+slc
http://apidocs.strongloop.com/loopback/
http://strongloop.com/strongblog/category/loopback-2/
https://github.com/ritch/loopback-foodme
http://docs.strongloop.com/display/LB/Data+sources+and+connectors
http://docs.strongloop.com/display/LB/LoopBack+example+app
http://docs.strongloop.com/pages/viewpage.action?pageId=3834790
http://docs.strongloop.com/display/LB/Use+API+Explorer
https://github.com/strongloop/loopback-explorer
http://docs.strongloop.com/display/LB/LoopBack+example+app
http://strongloop.com/mobile-application-development/loopback/
http://strongloop.com/strongblog/enterprise-api-swagger-2-0-loopback/
http://docs.strongloop.com/display/ARC/Create+models+with+Composer
http://docs.strongloop.com/display/ARC/Create+models+with+Composer#CreatemodelswithComposer-ViewendpointswithAPIExplorer
http://docs.strongloop.com/display/ARC/Build+and+deploy+application
http://docs.strongloop.com/display/ARC/Profile+application
http://docs.strongloop.com/display/ARC/View+application+metrics
http://strongloop.com/node-js/api-platform/
http://docs.strongloop.com/pages/viewpage.action?pageId=3834790
http://docs.strongloop.com/display/LGW/LoopBack+API+Gateway
http://docs.strongloop.com/display/ARC
http://strongloop.com/node-js/subscription-plans/

What is loopback? What is strongloop? What is strongloop arc?

Loopback is an open-source framework. Strongloop is the commercial company that make loopback. Strongloop Arc is one of the commercial product based on loopback.

What are the key benefits of using Strongloop Arc?

A graphical UI for the StrongLoop API Platform that complements the slc command line tools for developing APIs quickly and getting them connected to data. Arc also includes tools for building, profiling and monitoring Node apps.

StrongLoop API Platform allows you to visually develop REST APIs in Node and get them connected to your data. In addition, the API Platform features built-in mBaaS features like push and offline sync, plus graphical tools with DevOps features for clustering, profiling and monitoring Node apps.

Built-in mobile services like offline sync, push, geopoint, social login and replication accessible via native SDKs including iOS, Android and Angular.

Easily connect your APIs to Oracle, SQL Server, MongoDB, MySQL, PostgreSQL, SOAP and ATG with StrongLoop supported and community data connectors.

Graphical tools for debugging, profiling and tracing Node apps.

Graphical and command line tools for building, deploying, clustering and scaling Node apps.

APM capabilities like Event Loop monitoring, GC, CPU and Memory usage stats, response times and slowest endpoints either hosted or on-premise.

How to install strongloop?

npm install -g strongloop

How to start arc?

Go to the directory that contains your application and:

slc arc

Arc is run on http://localhost:51230. We are now ready to log into Arc. If you haven’t already registered, please do so by visiting http://strongloop.com/register/. Once you’re logged in you’ll see the Arc launchpad. Click on the “Composer” icon. That’s it! You are ready to start creating and discovering models. Here’s the step-by-step instructions for composing APIs with StrongLoop Arc.

How to create the sample application?

StrongLoop provides a sample application so that we can poke around a learn. To get StrongLoop to produce this sample application:

$ slc loopback:example
$ [?] Enter a directory name where to create the project: SampleApp
$ cd SampleApp
$ slc run

This will generate and start an example app in the “Sample App” or any specified folder. It’s good to run and poke around it to get a sense for the new library because the sample app comes with batteries included:

  • Example APIs to explore
  • Sample data to play with
  • Multiple data adapters (MongoDB, In-Memory, MySQL and OracleDB)
  • API explorer with auto-generated API endpoint methods for CRUD

Open up http://localhost:3000/explorer in a browser and you should be seeing API explorer which comes in a pluggable, but completely separate NPM module called loopback-explorer.

How to create a new skeletal application?

$ slc loopback

This will ask you for the name of your application, and the name of the directory where you want to store the application. This will generate skeleton LoopBack application (hence slc loopback). This is equivalent to rails new myapp.

What are the files generated by the "slc loopback" command?

  • server.js is our main file here where the whole application is set up. If you already have experience with express.js module, the file will look very familiar. There’s some LoopBack magic happens to help you get started faster following convention over configuration mantra that Rails users are accustomed to. There is a placeholder for a client Javascript application under /client
  • config.json - Global application settings, such as the REST API root, host name and port to use, and so on. See config.json.
  • model-config.json - Binds models to data sources and specifies whether a model is exposed over REST, among other things. See model-config.json
  • datasources.json stores the backend datasource settings while the config.json has the application host and port settings. Data source configuration file. See datasources.json.
  • client directory (empty except for a README stub)
  • common/models directory - created when you create a model with the Model generator, slc loopback:model. For each model, a JSON file and a JavaScript file are created (for example, my-model.json and my-model.js).

Models will be stored as .json files under /common/models and model-config.json retains the mapping of models to data-sources.

How to enable StrongLoops monitoring?

slc strongops

How to start the application?

slc run

Now go to http://localhost:3000/. You'll see the default application response that displays some JSON with some status information; for example:

{"started":"2014-11-20T21:59:47.155Z","uptime":42.054

Now open your browser to http://0.0.0.0:3000/explorer or http://localhost:3000/explorer. You'll see the StrongLoop API Explorer.

How to start the application in a multiprocess cluster?

If you want to run the server in a multiprocess cluster, use this command:

slc run --cluster cpus

How to add a remote method?

Open coffee-shop.js in your favorite editor. By default, it contains an empty function:

module.exports = function(CoffeeShop) {
};

Add the following code to this function to extend the model's behavior with a remote method, so it looks as shown here:

module.exports = function(CoffeeShop) {
  CoffeeShop.status = function(cb) {
    var currentDate = new Date();
    var currentHour = currentDate.getHours();
    var OPEN_HOUR = 6;
    var CLOSE_HOUR = 20;
    console.log('Current hour is ' + currentHour);
    var response;
    if (currentHour > OPEN_HOUR && currentHour < CLOSE_HOUR) {
      response = 'We are open for business.';
    } else {
      response = 'Sorry, we are closed. Open daily from 6am to 8pm.';
    }
    cb(null, response);
  };
  CoffeeShop.remoteMethod(
    'status',
    {
      http: {path: '/status', verb: 'get'},
      returns: {arg: 'status', type: 'string'}
    }
  );
};

This defines a simple remote method called "status" that takes no arguments, and checks the time and returns a JSON status message that says either "Open for business" or "Sorry we are closed depending on the current time. Of course, in practice you can do much more interesting and complex things with remote methods such as manipulating input data before persisting it to a database. You can also change the route where you call the remote method, and define complex arguments and return values. See Remote methods for all the details.

Go to http://localhost:3000/explorer to see API Explorer. Then click on CoffeeShops and you'll see there is a new REST endpoint, GET/CoffeeShop/status that calls the remote method.

How is Loopback middleware different from Express middleware?

LoopBack middleware is exactly like Express middleware, except that LoopBack adds the concept of phases, that enables you to easily set the order in which middleware is called. This avoids one of the tricky aspects of Express: making sure middleware gets executed when it should be.

When you create an application with slc loopback, it creates a server/middleware.json file that specifies what middleware is executed in which phase. Registering new middleware is as simple as editing this JSON file:

{
  "initial:before": {
    "loopback#favicon": {}
  },
  "initial": {
    "compression": {}
  },
  "session": {
  },
  "auth": {
  },
  "parse": {
  },
  "routes": {
    "loopback#status": {
      "paths": "/"
    }
  },
  "files": {
  },
  "final": {
    "loopback#urlNotFound": {}
  },
  "final:after": {
    "errorhandler": {}
  }
}

Each of the top-level keys in middlewre.json defines a middleware phase: initial, session, auth, and so on, ending with final. There are also modifiers to register middleware before and after a given phase. There's a bit more to it, but that covers the basics. See Defining middleware for all the details.

How to change or modify the default root route handler?

When you loaded the application root URL, http://localhost:3000/, you saw the application respond with a simple status message such as this:

{"started":"2014-11-20T21:59:47.155Z","uptime":42.054}

This happens because by default the scaffolded application has a boot script named root.js that sets up route-handling middleware for the root route ("/"):

module.exports = function(server) {  // Install a `/` route that returns server status
  var router = server.loopback.Router();
  router.get('/', server.loopback.status());
  server.use(router);
};

This code says that for any GET request to the root URI ("/"), the application will return the results ofloopback.status(). To make your application serve static content you need to disable this script. Either delete it or just rename it to something without a .js ending (that ensures the application won't execute it).

How to define static middleware to serve files in the /client directory?

Next, you need to define static middleware to serve files in the /client directory. Edit server/middleware.json. Look for the "files" entry:

...
  "files": {
  },
...

Add the following:

...
  "files": {
    "loopback#static": {
      "params": "$!../client"
  },
...

These lines define static middleware that makes the application serve files in the /client directory as static content. The $! characters indicate that the path is relative to the location of middleware.json.

Now, the pplication will serve any files you put in the /client directory as static (client-side) content. So, to see it in action, add an HTML file to /client. For example, add a file named index.html with this content:

<head><title>LoopBack</title></head>
<body>
    <h1>LoopBack Rocks!</h1>
    <p>Hello World... </p>
</body>

When you load http://0.0.0.0:3000/ now instead of the status JSON, you will see the Hello World page.

In which order does Loopback read and execute the scripts in the server/boot directory?

Alphabetical order. When a LoopBack application starts (or "bootstraps"), it runs the scripts in the /server/boot directory, known as boot scripts. By default, LoopBack loads boot scripts in alphabetical order.

How to add a custom Express route?

Add a new boot script named routes.js in /server/boot directory, with this code:

module.exports = function(app) {
  // Install a "/ping" route that returns "pong"
  app.get('/ping', function(req, res) {
    res.send('pong');
  });
}

As an aside, you could have just as well used Express router middleware instead, like this:

module.exports = function(app) {
  var router = app.loopback.Router();
    router.get('/ping', function(req, res) {
      res.send('pongaroo');
    });
    app.use(router);
}

In fact you can also add routes right in sever.js using the Express API. For example, add this call to app.use() just before the call to app.start():

...
app.use('/express-status', function(req, res, next) {
  res.json({ running: true });
});

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
}

What kinds of model relationship does Loopback support?

LoopBack supports many different kinds of model relations, including: BelongsTo, HasMany, HasManyThrough, and HasAndBelongsToMany, among others. For more information, see Creating model relations.

What happens to the model files when we create model relationships using "slc loopback:relation"?

The "slc loopback:relation" command automatically update the model files.

What is the definition of "remote hooks"?

Recall in Extend your API, you created a remote method—a custom function that you can call through a REST endpoint. A remote hook is simply a function that gets executed before or after the remote method.

You can define two kinds of remote hooks:

  • beforeRemote() runs before the remote method.
  • afterRemote() runs after the remote method.

In both cases, you provide two arguments: a string that matches the remote method you want to which you want to "hook" your function, and a callback function. Much of the power of remote hooks is that the string can include wildcards, so it is triggered by any matching method.

How can we implement a remote hook?

Here, you're going to define a remote hook on the review model, specifically Review.beforeRemote. Modify common/models/review.js, and add the following code:

module.exports = function(Review) {
  Review.beforeRemote('create', function(context, user, next) {
    var req = context.req;
    req.body.date = Date.now();
    req.body.publisherId = req.accessToken.userId;
    next();
  });
};

This function is called before a new instance of the Review model is created. The code:

  • Inserts the publisherId using the access token attached to the request.
  • Sets the date of the review instance to the current date.

What is the AngularJS SDK?

AngularJS is an open-source JavaScript model–view–controller (MVC) framework for browser-based applications. LoopBack provides an AngularJS JavaScript SDK to facilitate creating AngularJS clients for your LoopBack API server-side apps. The SDK is installed when you install StrongLoop.

The SDK provides auto-generated AngularJS services, compatible with ngResource.$resource, that provide client-side representation of the models and remote methods in the LoopBack server application. The SDK also includes some command-line tools, including lb-ng that generates Angular $resource services for your LoopBack application, creating in effect a dynamic client that automatically includes client-side APIs to access your LoopBack models and methods. You don't have to manually write any static code. For more information, see AngularJS JavaScript SDK.

Is there any differences between "remote hook" and "model hook"?

Need research.

How can we generate the lb-services.js file?

To generate the Angular services for a LoopBack application, use the AngularJS SDK lb-ng command-line tool. In the project root directory, enter this command:

$ lb-ng server/server.js client/js/services/lb-services.js

This command creates client/js/services/lb-services.js.

How can we turn off stack trace?

To turn this off, add this line to server/config.json:

loopback.rest({disableStackTrace: true});

Can we have a separate configuration file for each environment?

Yes. For example:

  • config.json
  • config.local.js
  • datasources.json
  • datasources.production.js
  • datasources.staging.js

You can override values that are set in config.json in:

  • config.local.js or config.local.json
  • config.env.js or config.env.json, where env is the value of NODE_ENV (typically development or production); so, for example config.production.json.

The additional files can override the top-level keys with value-types (strings, numbers) only. Nested objects and arrays are not supported at the moment.

Node uses the NODE_ENV environment variable.

How can we disable the API Explorer?

LoopBack API Explorer is great when you're developing your application, but for security reasons you may not want to expose it in production. To disable API Explorer entirely, if you created your application with the Application generator, simply delete or rename server/boot/explorer.js (perhaps by using your release script).

How can we customize REST error handling?

You can customize the REST error handler by adding the error handler callback function to config.local.js as follows:

module.exports = {
  remoting: {
    errorHandler: {
      handler: function(err, req, res, next) {
        // custom error handling logic
        // call `next()` to fall back to the default error handler
      }
    }
  }
};

How can we access an environment variable?

You can easily set an environment variable when you run an application like this:

$ MY_CUSTOM_VAR="some value" slc run
$ export MY_CUSTOM_VAR="some value"
$ slc run

Then this variable is available to your application as process.env.MY_CUSTOM_VAR.

How can we version our API?

You can easily add versioning to your REST API routes, based on the application "major" version in package.json. Add a file name config.local.js in the application's /server directory with the following code:

var p = require('../package.json');
var version = p.version.split('.').shift();
module.exports = {
  restApiRoot: '/api' + (version > 0 ? '/v' + version : ''),
  host: process.env.HOST || 'localhost',
  port: process.env.PORT || 3000
};

This takes the major version number from the version property in package.json and appends it to the REST API root. If your app's major version is 0, then the REST API root remains the default /api. So, for example, if version in package.json is 2.0.1, then the built-in model route exposed by default at:

GET http://localhost:3000/api/Users

is now exposed at:

GET http://localhost:3000/api/v2/Users

Changing the API root in this way doesn't affect routes set in request-handling middleware or the route to API Explorer itself, which remains http://localhost:3000/explorer.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License