Using Node.js to connect to a REST API

后端 未结 4 708
借酒劲吻你
借酒劲吻你 2020-12-13 16:15

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

4条回答
  •  青春惊慌失措
    2020-12-13 17:08

    /*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);
    
        }
    

提交回复
热议问题