10

Is it sensible to use Node.js to write a stand alone app that will connect two REST API's?

One end will be a POS - Point of sale - system

The other will be a hosted eCommerce platform

There will be a minimal interface for configuration of the service. nothing more.

1
  • Yes, it's ok. I don't see why you cannot use node.js for that purpose. Apr 22, 2013 at 13:31

4 Answers 4

30

Yes, Node.js is perfectly suited to making calls to external APIs. Just like everything in Node, however, the functions for making these calls are based around events, which means doing things like buffering response data as opposed to receiving a single completed response.

For example:

// get walking directions from central park to the empire state building
var http = require("http");
    url = "http://maps.googleapis.com/maps/api/directions/json?origin=Central Park&destination=Empire State Building&sensor=false&mode=walking";

// get is a simple wrapper for request()
// which sets the http method to GET
var request = http.get(url, function (response) {
    // data is streamed in chunks from the server
    // so we have to handle the "data" event    
    var buffer = "", 
        data,
        route;

    response.on("data", function (chunk) {
        buffer += chunk;
    }); 

    response.on("end", function (err) {
        // finished transferring data
        // dump the raw data
        console.log(buffer);
        console.log("\n");
        data = JSON.parse(buffer);
        route = data.routes[0];

        // extract the distance and time
        console.log("Walking Distance: " + route.legs[0].distance.text);
        console.log("Time: " + route.legs[0].duration.text);
    }); 
}); 

It may make sense to find a simple wrapper library (or write your own) if you are going to be making a lot of these calls.

2
  • I really warm to the node evented model. when data is chunked in like this. is it possible to begin manipulating it before the stream has ended? does it arrive in order? Apr 22, 2013 at 23:26
  • 1
    Thanks! Yes, the data is streamed in order. If you are able to use the data before streaming is complete, I don't see why you couldn't work with it before then (although I personally haven't had a use case for it yet). Apr 23, 2013 at 0:51
1

Sure. The node.js API contains methods to make HTTP requests:

I assume the app you're writing is a web app. You might want to use a framework like Express to remove some of the grunt work (see also this question on node.js web frameworks).

0
/*Below logics covered in below sample GET API    
    -DB connection created in class
    -common function to execute the query 
    -logging through bunyan library*/


const { APIResponse} = require('./../commonFun/utils');
    const createlog = require('./../lib/createlog');
    var obj = new DB();
    //Test API
    routes.get('/testapi', (req, res) => {
        res.status(201).json({ message: 'API microservices test' });
    });
    dbObj = new DB();
    routes.get('/getStore', (req, res) => {
        try {
            //create DB instance

            const store_id = req.body.storeID;
            const promiseReturnwithResult = selectQueryData('tablename', whereField, dbObj.conn);
            (promiseReturnwithResult).then((result) => {
                APIResponse(200, 'Data fetched successfully', result).then((result) => {
                    res.send(result);
                });
            }).catch((err) => { console.log(err); throw err; })
        } catch (err) {
            console.log('Exception caught in getuser API', err);
            const e = new Error();
            if (err.errors && err.errors.length > 0) {
                e.Error = 'Exception caught in getuser API';
                e.message = err.errors[0].message;
                e.code = 500;
                res.status(404).send(APIResponse(e.code, e.message, e.Error));
                createlog.writeErrorInLog(err);
            }
        }
    });

    //create connection
    "use strict"
    const mysql = require("mysql");

    class DB {
      constructor() {
        this.conn = mysql.createConnection({
          host: 'localhost',
          user: 'root',
          password: 'pass',
          database: 'db_name'
        });
      }

      connect() {
        this.conn.connect(function (err) {
          if (err) {
            console.error("error connecting: " + err.stack);
            return;
          }
          console.log("connected to DBB");
        });
      }
      //End class
    }

    module.exports = DB


    //queryTransaction.js File

    selectQueryData= (table,where,db_conn)=>{  
        return new Promise(function(resolve,reject){
          try{  
              db_conn.query(`SELECT * FROM ${table} WHERE id = ${where}`,function(err,result){
                if(err){
                  reject(err);
                }else{
                  resolve(result);
                }
            });
          }catch(err){
              console.log(err);
          }
        });
    }

    module.exports= {selectQueryData};

    //utils.js file

    APIResponse = async (status, msg, data = '',error=null) => {  
      try {
        if (status) {
          return { statusCode: status, message: msg, PayLoad: data,error:error }
        }
      } catch (err) {
        console.log('Exception caught in getuser API', err);
      }
    }

    module.exports={
      logsSetting: {
        name: "USER-API",
        streams: [
            {
                level: 'error',
                path: '' // log ERROR and above to a file
            }
        ],
      },APIResponse
    }

    //createlogs.js File

    var bunyan = require('bunyan');
    const dateFormat = require('dateformat');
    const {logsSetting} = require('./../commonFun/utils');

    module.exports.writeErrorInLog = (customError) => {
      let logConfig = {...logsSetting};
      console.log('reached in writeErrorInLog',customError)
      const currentDate = dateFormat(new Date(), 'yyyy-mm-dd');
      const path = logConfig.streams[0].path = `${__dirname}/../log/${currentDate}error.log`;
      const log = bunyan.createLogger(logConfig);
      log.error(customError);

    }
0
-1

A more easy and useful tool is just using an API like Unirest; URest is a package in NPM that is just too easy to use jus like

 app.get('/any-route', function(req, res){
     unirest.get("https://rest.url.to.consume/param1/paramN")
       .header("Any-Key", "XXXXXXXXXXXXXXXXXX")
       .header("Accept", "text/plain")
       .end(function (result) {
       res.render('name-of-the-page-according-to-your-engine', {
         layout: 'some-layout-if-you-want',
         markup:  result.body.any-property,
    });

});

2
  • "res" is undefined!
    – Kasra
    Jun 8, 2017 at 18:28
  • Yo must put it into a route in app.get('/', auth.protected, function (req, res){ });
    – scrodrig
    Jun 8, 2017 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.