Using StrongLoop to create a Node.js MySQL application

6 min read

By: Arpitha Myla

Using StrongLoop to create a Node.js MySQL application

<code>npm install -g strongloop</code>

The StrongLoop API Platform is built on top of the open source LoopBack.io, a highly-extensible, Node.js API framework. With LoopBack, you can quickly create scalable APIs and database mappings. StrongLoop also has built-in Mobile Backend as a Service (MBaaS) features like push and offline sync, and it has graphical tools for clustering, profiling and monitoring Node apps. StrongLoop runs on top of the Express Node.js web application framework and conforms to the Swagger 2.0 specification.

logo

The recently published tutorial Getting Started with Bluemix and StrongLoop presents videos summarizing the strengths of each product and demonstrating a sample application; the tutorial Getting Started with Node.js LoopBack Framework and IBM Cloudant examines how to leverage IBM Cloudant as a backend data store with the LoopBack framework and StrongLoop Arc tools.

Continuing with same theme as the previous tutorials, this brief tutorial shows the steps of integrating data from a MySQL database with Node.js using the StrongLoop API. We make no assumptions about tooling other than the command line! Once complete, you will be able to browse the generated APIs:

StrongLoop API

From there you will be able to POST data with the StrongLoop API Explorer and review the results in your database browser of choice.

Before you begin

Beyond the command line, below are the prerequisite tools:

  • A local Node.js installation (see the Node.js download or if you prefer an Eclipse environment, see the Nodeclipse download)

  • The Node.js executable npm, the package manager for Node.js

Of course you’ll need a Bluemix account. If you don’t already have one, click the button below:

Free Bluemix trial!

Before you can use StrongLoop in your app, you must install the StrongLoop command line tools. These include slc, the command shell for the StrongLoop Process Manager, strong-pm, and the LoopBack API Framework, with both a CLI and a GUI. To install the StrongLoop tools, execute the following npm command:

<code>npm install -g strongloop</code>

To verify whether LoopBack is installed successfully, type

<code>slc –v</code>

It should display the version of your StrongLoop installation.

Create a skeletal LoopBack application

Change to your development directory.

<code>cd &lt;development_directory&gt;</code>

Create a new application entitled ‘<alias>-loopback-example’ (e.g. amyla-loopback-example) by using the following command.

<code>slc loopback  &lt;alias&gt;-loopback-example</code>
Create a skeletal LoopBack application

Enter the application name and the installation directory to complete the initialization of your new StrongLoop project. You now have a complete Node.js StrongLoop application. Try to run your application and open the explorer page.

<code>cd &lt;alias&gt;-loopback-example<br>
node server/server.js<br>
</code>

If an error similar to “Cannot find module ‘loopback'” occurs, run npm install to install the prerequisite modules in the node_modules directory. Click the show/hide link to show the StrongLoop APIs that come available with your new application:

Cannot find module 'loopback'

Install the StrongLoop MySQL connector

Next, we will add MySQL support for the MySQL database to the project, by installing the LoopBack MySQL connector. Run the following command to install the StrongLoop MySQL connector:

<code>cd &lt;alias&gt;-loopback-example<br>
npm install --save loopback-connector-mysql<br>
</code>

Configuring the Datasource

Now the appropriate database support is added, you must configure the datasource with your database connection. Create and configure a new datasource named ‘AccountDb’.

<code>slc loopback:datasource AccountDb</code>

Enter to accept the default datasource name. For the database type, select MySQL.

database type

Create a Node.js Application and MySQL Service

Now we have a working StrongLoop application running on our localhost, and we are about to add a MySQL connection to the application, we must first create the MySQL instance that we want to connect to.

If you have already an existing MySQL database instance that you want to use, you can skip this step and use the MySQL credentials of your existing service instead.

I will create a new MySQL database instance in Bluemix. If you do not have a Bluemix account, sign up for a free Bluemix trial.

  • Login to the Bluemix console at console.ng.bluemix.net.

  • Go to the Dashboard.

  • Under ‘Cloud Foundry Apps’ click ‘CREATE APP’.

  • Select ‘WEB’.

  • Select ‘SDK for Node.js’ and click ‘CONTINUE’.

  • Enter the application name ‘<alias>-loopback-example’ at ‘APP NAME’ and click ‘FINISH’.

Wait until the app is finished staging.

  • Once the message ‘Your app is running’ is displayed, click on the Overview page.

  • Click on ‘ADD A SERVICE OR API’ or if you previously already created the MySQL service, click ‘BIND A SERVICE OR API’.

  • Search for ‘MySQL’ or scroll down to the Data & Analytics services.

  • Find and select the ‘ClearDB MySQL Database’ service.

  • Accept the defaults or rename the service and press ‘USE’ and confirm to ‘restage’ the application.

    Accept the defaults

Once you created the service, in the left menu of the application detail page, go to ‘Environmental Variables’ to see the MySQL service credentials. Or go to the Overview page, and in the service window, click the ‘Show Credentials’ link.

Configure the Datasource

In your application directory, open the server/datasources.json file, and add your datasource configuration. Copy the credentials for the ClearDB MySQL service or use your own MySQL Database credentials.

<code>{<br>
   &quot;cleardb&quot;: [<br>
      {<br>
         &quot;name&quot;: &quot;MyClearDBMySQLDatabase-5y&quot;,<br>
         &quot;label&quot;: &quot;cleardb&quot;,<br>
         &quot;plan&quot;: &quot;spark&quot;,<br>
         &quot;credentials&quot;: {<br>
            &quot;jdbcUrl&quot;: &quot;jdbc:mysql://&lt;database_subdomain&gt;.cleardb.net/&lt;database&gt;?user=&lt;username&gt;&password=&lt;password&gt;&quot;,<br>
            &quot;uri&quot;: &quot;mysql://&lt;username&gt;:&lt;password&gt;@&lt;database_subdomain&gt;.cleardb.net:3306/&lt;database&gt;?reconnect=true&quot;,<br>
            &quot;name&quot;: &quot;&lt;database&gt;&quot;,<br>
            &quot;hostname&quot;: &quot;&lt;database_subdomain&gt;.cleardb.net&quot;,<br>
            &quot;port&quot;: &quot;3306&quot;,<br>
            &quot;username&quot;: &quot;&lt;username&gt;&quot;,<br>
            &quot;password&quot;: &quot;&lt;password&gt;&quot;<br>
         }<br>
      }<br>
   ]<br>
}</code>

Add the credentials to the server/datasources.json file.

<code>{<br>
  &quot;db&quot;: {<br>
    &quot;name&quot;: &quot;db&quot;,<br>
    &quot;connector&quot;: &quot;memory&quot;<br>
  },<br>
  &quot;AccountDb&quot;: {<br>
    &quot;host&quot;: &quot;&lt;database_subdomain&gt;.cleardb.net&quot;,<br>
    &quot;port&quot;: 3306,<br>
    &quot;database&quot;: &quot;&lt;database&gt;&quot;,<br>
    &quot;password&quot;: &quot;&lt;password&gt;&quot;,<br>
    &quot;name&quot;: &quot;AccountDb&quot;,<br>
    &quot;user&quot;: &quot;&lt;username&gt;&quot;,<br>
    &quot;connector&quot;: &quot;mysql&quot;<br>
  }<br>
}<br>
</code>

Create the Data Model

Now the database is successfully added and the datasource configured, you can create the data model. The data model describes the schema or the data objects in your application. Each data object will have its own model in StrongLoop. The complete schema is the collection of models. Here we create a data model for the Account object.

<code>slc loopback:model Account</code>

Follow the prompts to configure the data model. For the model’s ‘base class’ use ‘PersistedModel’ and choose to expose the model via the REST API. Add the model properties as follows:

<code>Name: Account<br>
Datasource: AccountDb<br>
Base class: PersistedModel<br>
Expose via REST: Yes<br>
Custom plural form: Leave blank<br>
</code>

For Properties on the data model, create the following three properties.

<code>Property name: email<br>
Property type: string<br>
Required? Not required<br>
</code>
<code>Property name: createdAt<br>
Property type: date<br>
Required? Not required<br>
</code>
<code>Property name: lastModifiedAt<br>
Property type: date<br>
Required? Not required<br>
</code>
Create the Data Model

We now have the database support, the data source and the data model. With these, we can use Object Relation Mapping (ORM) to generate the database schema in MySQL from the data model, using the auto-migrate tool in StrongLoop.

Add a script to create the schema in the database.

Create a bin directory inside the ./server folder in your project root.

<code>cd server<br>
mkdir bin</code>

In the server/bin directory, create a file called automigrate.js with the following code.

<code>var app = require('../server');<p></p>
<p>var accounts = [<br>
  {<br>
    email: 'foo@bar.com',<br>
    createdAt: new Date(),<br>
    lastModifiedAt: new Date()<br>
  },<br>
  {<br>
    email: 'baz@qux.com',<br>
    createdAt: new Date(),<br>
    lastModifiedAt: new Date()<br>
  }<br>
];</p>
<p>// this loads the accountDb configuration in ~/server/datasources.json<br>
var dataSource = app.dataSources.AccountDb;</p>
<p>// this automigrates the Account model<br>
dataSource.automigrate('Account', function(err) {<br>
  if (err) throw err;</p>
<p>  // this loads the Account model from ~/common/models/Account.json<br>
  var Account = app.models.Account;<br>
  var count = accounts.length;<br>
  accounts.forEach(function(account) {<br>
     // insert new records into the Account table<br>
     Account.create(account, function(err, record) {<br>
      if (err) return console.log(err);</p>
<p>      console.log('Record created:', record);</p>
<p>      count--;</p>
<p>      if (count === 0) {<br>
        console.log('done');<br>
        dataSource.disconnect();<br>
      }<br>
    });<br>
  });<br>
});<br>
</code></p>

Create the MySQL Schema

Run the automigrate.js script with the below command to create the table in MySQL.

<code>node server/bin/automigrate.js</code>
Create the MySQL Schema

After running the above script, connect to your MySQL database with your favorite MySQL client and you should see the table ‘account’ with the three columns: ’email’, ‘createdAt’ and ‘lastModifiedAt’. StrongLoop also added an ‘id’ column. The table has data for the two entries that we created in the script to insert the data:

MySQL database

Run the application

<code>slc run</code>

or

<code>node server/server.js</code>

and browse to http://localhost:3000/explorer. StrongLoop added a series of APIs that are Swagger compliant to your application to access the Account resource:

Account resource

We can also use the explorer page to test each API. Click the ‘POST /Accounts’ link to insert new data. Enter a new JSON record and press ‘Try it out!’.

<code>{<br>
  &quot;email&quot;: &quot;your@email.com&quot;,<br>
  &quot;createdAt&quot;: &quot;2015-09-01&quot;,<br>
  &quot;lastModifiedAt&quot;: &quot;2015-09-01&quot;<br>
}</code>
Try it out!

Your StrongLoop application to manage Accounts is done! We just need to still upload and deploy it to Bluemix.

Deploy the StrongLoop app to Bluemix

  • Go to the Bluemix Dashboard and click on the project(that you created earlier).

  • Click on start coding.

  • Download the code of the starter application in Bluemix to your localhost, or clone the Git repository to your localhost.

  • Copy the manifest.yml file of the Bluemix starter application to the root directory of your local StrongLoop application ‘<alias>-loopback-example’. This file contains information used by Cloud Foundry to deploy the Node.js application to Bluemix.

  • Copy the hidden .cfignore file to the root directory of your local StrongLoop application ‘<alias>-loopback-example’.

  • Modify the local StrongLoop ‘package.json’ file to add the ‘cfenv’ dependency and change the start script parameter (see code snippet below)

  • Modify server/server.js file of your local StrongLoop application to include the ‘host’ and ‘port’ read by cfenv. Bluemix makes these parameters available as environment variables. In the code snippet below I modified the server.js generated by StrongLoop to reflect these changes.

  • Remove the node_modules folder from the root directory of your local StrongLoop application.

Code snippet for package.json:

<code>&quot;scripts&quot;: {<br>
  &quot;start&quot;: &quot;node server/server.js&quot;,<br>
  &quot;pretest&quot;: &quot;jshint .&quot;<br>
 },<br>
&quot;dependencies&quot;: {<br>
  ..<br>
  &quot;cfenv&quot;: &quot;1.0.x&quot;<br>
  ..<br>
</code>

Code snippet for server/server.js:

<code>var loopback = require('loopback');<br>
var boot = require('loopback-boot');<br>
// cfenv provides access to your Cloud Foundry environment<br>
// for more info, see: https://www.npmjs.com/package/cfenv<br>
var cfenv = require('cfenv');<br>
// get the app environment from Cloud Foundry<br>
var appEnv = cfenv.getAppEnv();<p></p>
<p>var app = module.exports = loopback();<br>
app.start = function() {<br>
  // start the web server<br>
  return app.listen(appEnv.port, appEnv.bind, function() {<br>
    app.emit('started');<br>
    console.log('Web server listening at: %s', app.get('url'));<br>
  });<br>
};</p>
<p>// Bootstrap the application, configure models, datasources and middleware.<br>
// Sub-apps like REST API are mounted via boot scripts.<br>
boot(app, __dirname, function(err) {<br>
   if (err) throw err;<br>
    // start the server if `$ node server.js`<br>
   if (require.main === module)<br>
     app.start();<br>
});<br>
</code></p>

Connect to Bluemix and login to Bluemix:

<code>cf api https://api.ng.bluemix.net<br>
cf login -u &lt;alias&gt; -o &lt;organization&gt; -s &lt;space&gt;<br>
</code>

Push your application to Bluemix using the cf push command:

<code>cf push &lt;alias&gt;-loopback-example</code>

The cf push should kick off a git commitgit push and build and deploy on Bluemix. Check your Bluemix Dashboard or your JazzHub ‘Build & Deploy’ page to confirm your application is now running successfully on Bluemix!

Be the first to hear about news, product updates, and innovation from IBM Cloud