Smarter ideas worth writing about.

Building an API with Strongloop-Loopback Over NodeJS - Part II

In my last post, we went over how to create a default API with loopback.  Now were going to flesh out our API using models.

Step 1 – Requirements:
We’re trying to create something that allows users to enter and read reviews on gym/health clubs and give ratings as well.  If you have traditional background in OOL (Object Oriented Languages), we want to think what classes we need to create to represent the business logic.  Let’s start with the following:

  1. Users – already out of the box with loopback, so this is taken care of.
  2. Facility – The gym/health club
    1. Name – string
    2. Address – string
    3. Zip – string
  3. Review – A review of a gym.
    1. Title – string
    2. CreatedDate – date
    3. Pros – string
    4. Cons – string
    5. Rating – number
    6. UserID – number
    7. FacilityID – number

Step 2 – Model Creation (via StrongLoop CLI):

Models in loopback ultimately represent the data we are trying to retrieve/update (think ORM). You can create models manually or by using the SLC model generator at the command line. First we’re going to create the facility model by typing slc loopback:model the command prompt.  This is followed up by slc asking you a bunch of questions in order to stub out a model (example screenshot to the right).  When you’ve entered in all the property name/types you need or want, simply hit enter on the last time to exit.


Tips:

  1. If you forget to add a property, you can use slc loopback:property
  2. If you have a pre-existing database, some functionality exists to reverse engineer models either from a relational DB or unstructured DB as long as a connector exists for the DB.

All custom models are found in the \common\models folder. We’re going to cover what slc actually created from in the last step, which is what you would do manually.

  1. Go to the \common\models folder and create a model definition JSON file for the facility model.  (More in depth info) 

  2. facility.json
    {
     "name": "Facility",
     "plural": "Facilities",
     "base": "PersistedModel",
     "idInjection": true,
     "options": {
     "validateUpsert": true
     },
     "properties": {
     "Name": {
     "type": "string",
     "required": true
     },
     "Address": {
     "type": "string",
     "required": true
     },
     "Zip": {
     "type": "string",
     "required": true
     }
     },
     "validations": [],
     "relations": {},
     "acls": [],
     "methods": []
    }
    

  3. Next create a JS file. This is where custom methods will be implemented.

  4. facility.js
    module.exports = function(Facility) {
     
    };
    

  5. Goto the \server directory and update the below file with the highlighted code:

    model-config.json
  6. ...
    "Role": {
    "dataSource": "db",
    "public": false
    },
    "Facility": {
    "dataSource": "db",
    "public": true
    }
    ...

Step 3 – Test Drive:
If we run our application now and head over to http://localhost:3000/explorer, you’ll notice the the model we’ve added is new.  Out of the box, if you click on “Facilities," you’ll notice quite a few CRUD operations are already done for us.  You create a facility by performing a post (either through the explorer or something like Fiddler) and then perform a get to see what you just created.

Strongloop explorer showing the Facility model.


Step 4 – Data Storage:
At this point you probably want to add the Facility model, but let’s hold off on that.  Since the Facility model was defaulted to in memory, restarting the app will clear any data entered.  Let’s use mongoDB to store our data for the model we just created.

  1. At the command line, enter slc loopback:datasource and give it a name of your choosing (I’ll use myMongoDB) and select MongoDB as the connector.
  2. Open up the \server folder and you’ll notice the below file has changed 

  3. datasources.json
    {
     "db": {
     "name": "db",
     "connector": "memory"
     },
     "myMongoDB": {
     "name": "myMongoDB",
     "connector": "mongodb"
     }
    }
    

  4. The slc added a new connection called "myMongoDB" which uses a "mongdb," but it doesn't do anything yet. Now we need to add connection information (obviously change your credentials based on your datasource)

  5. datasources.json
    {
     "db": {
     "name": "db",
     "connector": "memory"
     },
     "myMongoDB": {
     "name": "myMongoDB",
     "connector": "mongodb",
     "host": "localhost",
     "port": 27017,
     "database": "MobileApiTest",
     "username": "apiUser",
     "password": "YourPasswordHere"
     }
    }
    

  6. Update your \server\model-config.json file and update the highlighted. The name of the datasource correspondes to the name given  in the 2nd step.

  7. model-config.json
    ...
    "User": {
     "dataSource": "myMongoDB"
     },
    ...
     "Facility": {
     "dataSource": "myMongoDB",
     "public": true
     },
    

  8. (Optional) You can also initialize your datasource by placing a file into the \server\boot folder. Loopsbacks calls this process Auto-Migration which can be userful (e.g. - scripting initial data for demo apps).

  9. module.exports = function(app) {
     //MongoDB automigration and collection initialization
     app.dataSources.myMongoDB.automigrate('Facility', function(err) {
     if (err) throw err;
      
     //Creating Facility Data
     app.models.Facility.create([
     {Name: "Gold's Gym", Address: '1000 Fitness Rd.', Zip: '27001'},
     {Name: "YMCA", Address: '1001 Fitness Rd.', Zip: '27001'},
     {Name: "Anytime Fitness", Address: '1002 Fitness Rd', Zip: '27001'}
     ], function(err, facilities) {
     if (err) throw err; 
     console.log('Facilities created: \n', facilities);
     });
     };
     });
    

Step 5 – Testing (with Data):
Restart the API and if you perform a GET request on the Facility Model, you’ll notice data already exists because of the script we added to the \server\boot folder. Performing other CRUD operations will now be reflected in your MongoDB.
(NOTE: If you don’t comment/remove your script in the boot folder, it will drop and recreate your tables/collections.)

From here going forward, you can repeat the process above in step 2 to create the Facility model.  You will notice is that if you are using SLC that mongoDB will now be an option when being asked to select a datasource.



Share:

About The Author

Software Developer

As a software developer, Timothy supports the App Dev team in Cardinal's Raleigh office. The majority of his experience has been with the Microsoft stack, but he has also been working on RESTful service development on current mobile initiatives.