Developing a Loopback Rest Api backend (part 1/n)

Introduction

In the previous article, we developed an AngularJS client which we connected to a LightSwitch Odata back-end.

Let’s work now the other way around and use an alternative backend:  Loopback.

What is Loopback?

Loopback is a super-de-lux extensible NodeJS framework for creating REST APIs.

Ok, you might have some cold-water fear, as I did, when jumping on the NodeJS bandwagon, but I can assure you it’s worth investing the time. You’ll see soon that NodeJS is an extremely simple but powerful instrument.

I’ll try to guide you to a working sample in an concise manner. I’ll avoid any IDE’s in this article, we’ll just do everything with notepad, that keeps us down to earth.

step 1 : Install NodeJS

I don’t suspect I have many mac or Linux readers, but just in case… continue reading, because everything covered in this article will work as well on a mac or on a Linux machine.

Go to the NodeJS website and follow the instructions. Make sure that the Node executable is added in your Path variable so you can start it from everywhere. This is normally done automatically:

nodeinstall

 

Note that NodeJS comes with an installer of 6 mega Byte, the size of an average Selfie.

I can assure you that the functionality per square bit will make you hallucinate….

 

Let’s first do a quick test if NodeJS is correctly functioning. You can find the same test on the NodeJS website.

Open a command prompt in an empty folder of your choice:

command1

create a server.js file inside that folder by typing: notepad server.js

command2

Copy paste following content in server.js:

var http = require('http');
http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('In search for an alternative backendn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Start node with the newly created server.js : Node server.js

command3

 

Open now a browser and go to http://localhost:1337 and you’ll see a working though very simple web application.

 

Sit back and relax now

Although the above is quite impressive when looking to the amount of time needed for setting up a full web application server, we are still far from a full-fledged line of business application server side framework.

Typically ExpressJS is here the candidate for filling this gap. ExpressJS is a great framework, but it’s all “configuration over convention”, you must opt-in on every piece of functionality. Believe me, learning all this, is an investment. We need something simpler without losing flexibility.

 

Bringin in dependencies with Npm

When you work a lot with visual studio, you definitely know Nuget. That’s a package manager. NodeJS has something similar and it’s called Npm (Node Package modules).

Basically, the Loopback client tool will be installed with Npm (we’ll do this in a minute).

 

Getting Started with Loopback

First create another folder of re-use the same folder (but delete server.js or make backup if you really like the app).

Go now to the getting started page of Loopback.io and simply follow the instructions.

I just did the first instruction a bit differently. NodeJS packages are c++ based, the Npm installer will sometimes compile stuff.

When you do instead of : npm install -g strongloop  :

npm install -g strongloop  –msvs_version=2013

you instruct NPM to use visual studio 2013 when there is c++ compiling necessary.

Walk now through the getting started, it’s extremely short. You will be asked for a type to be created. Call it “customer”, all in lowercase (very important!).

We will be creating a customer entity with 4 properties:

  • firstName (type:string)
  • lastName (type:string)
  • created (type: date)
  • updated (type: date)

 

When you are finished with the getting started, we will update now 2 files in such a way that we are sure we are working with the same stuff. In case you started the app already (by typing slc run), just stop the app by pressing Control-C.

 

Locate inside the ./common/models folder the files customer.js and customer.json

common

 

 

Open with your favorite text editor the customer.json file and replace the content with following content:

{
"name": "customer",
"plural": "customers",
"base": "PersistedModel",
"properties": {
"firstName": {
"type": "string",
"required": true
},
"lastName": {
"type": "string",
"required": true
},
"created": {
"type": "date"
},

"updated": {
"type": "date"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}

 

If you did the “getting started” correctly, you should have the same content anyhow.

 

The next (and last) file we will update is the customer.js file. What we want is to instruct the server engine to insert automically some audit fields when we create or update a customer. We simply use a create and update time stamp.

So, open customer.js and update as follows:

module.exports = function (Customer) {

       Customer.beforeCreate = function (next, model) {
         model.created = Date.now();
         next();
     };
     Customer.beforeUpdate = function (next, model) {
         model.updated = Date.now();
         next();
     };
};

Note the typical call-back pattern in the beforeCreate and beforeUpdate function. Everyting is node is async !

Restart the app now by typing : slc run.

Let’s explore the api

Surf with a browser to http://localhost:3000/explorer

explorer1

 

 

Together with the customer entity, you’ll find a Users entity which we did not create explicitly. This gives already the indication that Loopback (or StrongLoop) is prepared for authentication, authorization and user management. Cool !

 

Click now on customers.

explorer2

 

and you’ll find a whole series of Rest operations that can be applied on our customer entity. Obviously, these operations can be applied from e.g. an AngularJS app (my preferred framework).

 

Let’s try to add a customer via this explorer window:

explorer3

You only need to provide the firstName and lastName field since created, updated as well as the id field will be auto created. Click on try it out.

 


explorer4b

We get back aresponse and we can verify that the created property has been filled in !

Alternatively we can simply browser to http://localhost:3000/api/customers to get the same result in json format.

 

explorer5

 

What’s my view on this.

I simply love this. What was the incremental effort to create from scratch a server side app?  Did we write any boiler plate code, configure object relational mappers, routing tables,… you name it ?

Nada, only the code which really matters was provided by us (and even created by the Client tooling. by the way StrongLoop has also a fancy entity designer.)

What’s next?

This version uses an in memory database. That’s good for this first test but obviously we’ll use a real database soon. We will seen that doing this will be extremely simple.

Stay tuned !