Recipes for LoopBack Models, part 2 of 5: Models with Schema Definitions

Last time, we looked at how you can mobilize data through LoopBack with open models, which works well for free-form style data.  This time around, we are looking at models with schema definitions.

I want to build a mobile application that will interact with some backend data. I would love to see a working REST API and mobile SDK before I implement the server side logic.

In this case, we’ll define a model first and use an in-memory data source to mock up the data access. You’ll get a fully-fledged REST API without writing a lot of server side code.

The snippet above creates a ‘Customer’ model with a numeric id, a string name, an array of string emails, and a numeric age. Please also note we set the ‘strict’ option to be true for the settings object so that LoopBack will enforce the schema and ignore unknown ones.

For more information about the syntax and apis to define a data model, check out:

http://docs.strongloop.com/loopback-datasource-juggler/#loopback-definition-language-guide

You can now test the CRUD operations on the server side. The following code creates two customers, finds a customer by ID, and then finds customers by name to return up to three customer records.

To expose the model as a REST API, use the following:

Until now the data access has been backed by an in-memory store. To make your data persistent, simply replace it with a MongoDB database by changing the data source configuration:

For more information about data sources and connectors, please check out:

http://docs.strongloop.com/loopback-datasource-juggler/#loopback-datasource-and-connector-guide

When defining a model, it may be troublesome to define all the properties from scratch. Fortunately, LoopBack can discover a model definition from existing systems such as relational databases or JSON documents, as we’ll show in part 3 next week.

What’s next?

Recipes for LoopBack Models, Part 1 of 5: Open Models

Rich mobile applications are driven by data. Data can be produced and consumed by mobile devices, browsers, cloud services, legacy applications, databases, and other backend systems.

LoopBack mobilizes data through models that represent business data and behavior. LoopBack exposes models to mobile apps through REST APIs and client SDKs. You need to interact with the model differently, depending on the location and type of data. In this 5-part blog series, I’ll explain some of the most important recipes for working with LoopBack models:

  • Part 1: Open models – for free-form data.

  • Part 2: Models with schema definitions such as relational databases.

  • Part 3: Model discovery with relational databases – consuming existing data from a relational database.

  • Part 4: Models by instance introspection – Consuming JSON data from NoSQL databases or REST APIs.

  • Part 5: Model synchronization with relational databases – keeping your model synchronized with the database.

The source code is available at https://github.com/strongloop/loopback-sample-recipes.

Let’s start with the simplest one: open models.

I’m mobile developer. Can LoopBack help me save and load data transparently? I don’t need to worry about the backend or define the model up front, because my data are free-form.

For free-form data, use an open model that allows you to set any properties on model instances.

The following code creates an open model and exposes it as a REST API:

Notice the call to ds.createModel() with only a name to create an open model.

To try it out, enter the following command:

This command POSTs some simple JSON data to the LoopBack /forms URI.

The output that the app returns is a JSON object for the newly-created instance.

The id field is a unique identifier you can use to retrieve the instance:

Note: Your ID will be different as it is generated by the database. Please copy it from the POST response.

Try submitting a different form:

Now you see the newly created instance as follows:

For the complete list of REST APIs that LoopBack scaffolds for a model, please read:

http://wiki.strongloop.com/display/DOC/REST+API

If you have StrongLoop Suite (http://strongloop.com/strongloop-suite/downloads/)  installed, you can build and run this project from scratch in 5 commands:

Now open a browser and point it to http://localhost:3000/explorer.

You get an explorer to try the forms APIs right away. The UI is pretty straghtforward, feel free to play with it. For more information, check out:

http://wiki.strongloop.com/display/DOC/LoopBack+API

The open model is simple and flexible. It works well for free-form style data because the model doesn’t constrain the properties and their types. But for other scenarios, a predefined model is preferred to validate the data and ensure it can be exchanged among multiple systems.

Next week, we’ll talk about models with schema definitions.

What’s next?

Deploying LoopBack mBaaS on Rackspace

Fanatical Support Meets Strong Node

Fanatical Support has made Rackspace the leader in enterprise hosting. The Fanatical Support mantra, support for open source products, and strong SLA has made them the preferred vendor for IT ops in companies large and small. StrongLoop is excited to be one of the first available Node providers for their new Deployments service, which allows you to create and configure your multi machine Node topology in minutes.  StrongLoop Suite integration in the Control Panel means you’re 3 clicks from Strong Node, Strong-Ops, and LoopBack.

Push button, receive server

The easiest way for Rackspace customers to start using Node is via the Rackspace Control Panel. Log into your console at https://mycloud.rackspace.com and select “Deployments” view on the right of the control panel.  The Rackspace Deployment Service is a new offering that makes it easy to automate the launching of your app in the Rackspace cloud. It works great with the StrongLoop Suite by automating an application and resource deployment in a best practice configuration.

To Startup a Rackspace hosted StrongLoop Application, login into your myCloud.rackspace.com control panel and select  ‘Deployments’ on the right side of the Servers bar.

Rackspace-create-deployment

From the Rackspace “Create Deployment” panel insert your deployments name and select your region. Click the “StrongLoop LoopBack” Blueprint.

Rackspace-create-options

Then configure your StrongLoop server deployment options: Site Address, Admin settings and application name.ConfigurationOptions

Select your Deployment machine options.

Infrastructure-Details

Click the “Create Deployment” button to provision your server.

Fortunately the StrongLoop install pack is very lightweight so your newly configured StrongLoop Node server will be ready in a few minutes.  When you see the Server Status “go Green” you know your server is up and waiting for you.

 

Start Server, receive Open Node MBaaS

Now that you’re newly created StrongLoop server is up.  Lets take a look at what you get.

The StrongLoop Suite has three main components:  StrongNode, StrongOps and – most important for this posting – LoopBack.  LoopBack is an open source Mobile API tier.  The rest of this post will show you how to configure your loopback server and connect it to a Native iOS mobile application.

First take note of the public IP address that is presented to you once your server is activated.

We will use this IP address to configure the native mobile adapter allowing the iOS LoopBack SDK to connect to your mobile backend.  Let’s download the iOS example apps from the https://github.com/strongloop-community/loopback-examples-ios Github repo.  The LoopBack examples Repo has sample code to show you how to connect your mobile application to the LoopBack server using the native LoopBack SDK.  You can find additional documentation about LoopBack and the iOS SDK at the StrongLoop docs site docs.strongloop.com .  This article will show you how to connect to the UITableView example, however configuring the MapView and custom remote method sample can easily be configured.

iphone-examples-3

Once you have the repository cloned to your iOS development machine.

$git clone git@github.com:strongloop-community/loopback-examples-ios.git

Open the tableview-example.xcodeproj located at ‘loopback-examples-ios/ios-tableview-simple-example/tableview-example.xcodeproj’

The loopback-examples-ios applications has a LoopBack mobile server bundled with the repo ‘/loopback-examples-ios/loopback-nodejs-server’ that can be run on the developers host machine by calling ‘slc run app.js’ from within the server folder.  However, for this demo we will be leveraging our newly-provisioned LoopBack instance on the RackSpace cloud infrastructure.

Verify the Loopback server is running on the rackspace installation and the ‘products’ endpoint is available.  Open a web browser and point it to the LoopBack API explorer that come pre-configured with your LoopBack instance http://HOST-IP-ADDRESS:3000/explorer/.

LoopBack-Explorer-Products-Post

Now that you have your StrongLoop Suite (Strong-Node, Strong-Ops and LoopBack) up and configured in your Rackspace environment, you can simply configure the native iOS application to point to the mobile API.

From within XCode project open the AppDelegate.m file and configure the adapter URL to “http://RACKSPACE_IP_ADDRESS”.

iOS-ConfigureAdapter

Run the Application in the XCode iOS simulator with by Pressing the Run button in the top left or using the hotkey combination (?+R) . From the simulator Click the ‘Inject Data’ button in the top left to insert 3 ‘product’ model instances into the LoopBack server.  Naturally you will see the Records appear on the mobile device, but you can also verify the server content by opening the API Explorer http://localhost:3000/explorer/#!/products/products_find_get_4  to the Get Request and pressing the ‘Try it out’ button.

Screen Shot 2013-09-17 at 7.51.47 AM

Additionally, you can add data to the backend from the API Explorer as well from the ‘POST’ button by inserting the model JSON data { “name”: “Matts Product”, “inventory” : 22 }  in the ‘Value’ field. Pressing Refresh on the mobile client will sync the tableView.

Notice the model definition is dynamic, allowing the mobile developer to dynamically add parameters to the ‘product’ mobile model type; allowing the mobile developer to quickly extend and configure the Mobile Object to fit the applications need.  LoopBack also supports static schema configuration for situations where the model data may be directly bound to a traditional static data stores such as Oracle or MySql.

Take some time and explore the mobile application as well as the LoopBack Node server. You can find more detailed information on how LoopBack handles both static and dynamic model types at http://docs.strongloop.com/loopback/#sanitizing-and-validating-models ,and make and try give the integration a run on Rackspace

 

What’s next?

Deploying LoopBack mBaaS on Cloud Foundry

Getting Started with LoopBack on Cloud Foundry

cloud_foundry_logo

Most mobile developers want to focus on the front-end of their apps and not get caught up in having to figure out how to write a backend, connect it to data sources or worse how to manage and scale it. By deploying StrongLoop’s LoopBack mobile backend-as-a-service (mBaaS) on Cloud Foundry it’s possible to take advantage of an open, private mBaaS on an open and scalable platform-as-a-service.

What is Cloud Foundry?

Unlike many cloud providers, Cloud Foundry is an open source PaaS, providing a choice of supported clouds, developer frameworks and application services. Cloud Foundry makes it faster and easier to build, test, deploy and scale mobile backends like StrongLoop’s LoopBack. It is an open source project and is available through a variety of private cloud distributions and public cloud instances.

Why run LoopBack on Cloud Foundry?

If you are a mobile developer looking to develop applications that need access to data that resides in the cloud and the datacenter, there’s quite a few advantages to running your own private mBaaS in the cloud:

  • LoopBack is open source and extensible at its core and with the over 41,000 available NPM community modules, the possibilities are almost limitless

  • LoopBack is built on Node.js, so if you know JavaScript you know LoopBack

  • Out-of-the-box, LoopBack connects to enterprise datasources like Oracle and MongoDB

  • LoopBack ships with an iOS SDK, so you won’t have to compromise on functionality or inherit a steep learning curve

  • Cloud Foundry lets you focus on your app not machines or middleware

  • Cloud Foundry manages the patching, load balancing and availability of your backend

  • If your app needs it (and let’s hope it does!), Cloud Foundry auto-scales on demand to make sure whether you are servicing one or tens of thousands of users – everyone is guaranteed to have a stellar user experience

Configuring for Cloud Foundry and StrongLoop

First step is to install and configure the CF tools on your dev machine:

1. Register at StrongLoop.com and download the StrongNode distro for your development environment.

StrongLoop-Web-Downloads

2. Install the Cloud Foundry CLI common referred to as cf ( *you need Ruby 1.9.3 , OSX comes with Ruby v1.8.7 installed out of the box a small gist to help you with upgrade options for Mac)

$gem install cf

3. configuring your target ( you will need cf target, I’m using pivotal  https://console.run.pivotal.io/register  for this demo)

$cf target api.run.pivotal.io cf login <email> <password>

More information on Deploying Node.js Applications on CF

CF Push, For the Win

Build your LoopBack mBaaS on your local developer machine and push it to a Cloud Foundry PaaS

1.Create and Prepare your StrongLoop LoopBack Node application on your local machine

$mkdir CloudFoundryApp
$cd CloudFoundryApp
$slc lb api-example
$cd sls-sample-app
$slc install

2. Verify your LoopBack Mobile API tier is up and running by hitting the API explorer page on your local machine at http://localhost:3000/explorer

LoopBack-Explorer-Products-Post

3.Push your StrongLoop Application to the cloud

$cf push my-new-app

Start Server, receive Open Node MBaaS

Now that your newly created StrongLoop server is up, let’s take a look at what you get and connect your Cloud Foundry hosted MBaaS to a native Mobile iPhone app

Since you have the ‘loopback-mobile-getting-started’ github repo on your local machine  you can simply open the loopback iOS guide app located at /loopback-ios-app/loopback-ios-multi-model.xcodeproj with XCode.

Once the XCode Project is open you will need to modify your Adaptor endpoint to point to your server.   Modify the ‘

_adapter = [LBRESTAdapter adapterWithURL:[NSURL URLWithString:@”http://localhost:3000″]];’ in the AppDelegate.m.  Change the ‘localhost’ address to point to your  ip address.

Hit command R in XCode and walk through the walk the guide application instructions.

Sample-getting-started-ios-all

 

If you would like to find some more examples on how to integrate native iOS applications with LoopBack make sure and check out the http://github.com/strongloop-community/loopback-examples-ios , where you will find a UITableView, MapView and custom method call samples.

sample-examples-ios-all

If you are using a cross platform mobile tool such as Appcelerator Titanium ( javascript) or Xamarin ( c# )  make sure and check out our other examples at github.com/strongloop-community .

Now that you have your StrongLoop Suite ( StrongNode, StrongOps and LoopBack ) up and configured you can start building out your mobile client application. You can identify ‘hot spots’ and latency with StrongOps or look for stress inside your node.js server application code. You can customize your services and data by extending the open source Node LoopBack API tier with custom code or NPM modules from the community.

What’s next?