a blog for those who code

Tuesday 21 March 2017

Create a Node.js Micro Service for your Mobile App

In this post we will be discussing about creating a very simple Node.js Micro-service for your mobile app. Micro-service will be useful because then you need have to write any sensitive information inside your app like Access Token etc. Micro-service is a single self-contained unit which can be independently deploy-able and scalable.

Advantages of using Micro services is that now you need to have smaller code base, the micro-services are easily scalable and they are easily deploy-able. We will be using Micro npm package, which helps in creating async ES6 HTTP micro-services in Node.js. It has very nice features like its easy to understand, its fast, can be deployed very easily and is lightweight.

Install Micro

npm install micro -g

Using Micro-service

Now your mobile app wants to connect to twitter api to get top 10 twitter trends from a particular place (e.g. India). To do this we need a micro-service which will do the authentication for me and send back the data from the micro-service. Its better not to keep your sensitive information inside our mobile app. So lets develop the micro-service.

var https = require('https');
var micro = require('micro');
var headers = {
  'User-Agent': 'Coding Defined',
  Authorization: 'Bearer ' + require('./oauth.json').access_token
};

function callTwitter(options, callback){
  https.get(options, function(response) {
    jsonHandler(response, callback);
  }).on('error', function(e) {
    console.log('Error : ' + e.message);
  });
}

var trendOptions = {
  host: 'api.twitter.com',
  path: '/1.1/trends/place.json?id=23424848',
  headers: headers
}

function jsonHandler(response, callback) {
  var json = '';
  response.setEncoding('utf8');
  if(response.statusCode === 200) {
    response.on('data', function(chunk) {
      json += chunk;
    }).on('end', function() {
      callback(JSON.parse(json));
    });
  } else {
    console.log('Error : ' + response.statusCode);
  }
}

module.exports = function(req, res) {
  callTwitter(trendOptions, function(trendsArray) {
    micro.send(res, 200, trendsArray[0].trends)
  });
}


In the above code we are calling the twitter API to get the trends of India and then using the module.exports we are sending back the json.

Next is to run the file using the command micro tweets.js

Running Micro through command line

Running the Micro Service

Next is to deploy our service to server. You can use Heroku for deploying your Node.js Microservice.

Please Like and Share the CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment