0

我正在用 nodejs 编写服务。请阅读以下内容,了解我为解决此问题而采取的方法。

首先,我调用一个休息端点(比如 /offers)来获取数据。说它 cloudSenseData

最终响应我需要按摩/操作数据以将所需的响应作为输出返回。

在按摩数据(来自上述调用)期间,我必须检查是否存在相关产品信息。

如果存在,我需要调用另一个休息端点(例如 /offers/:id/products), :id 是在先前调用(cloudSenseData)中获得的目录项,以获取更多相关的产品信息详细信息,我可以将其包含在最终的按摩输出中。

所以让我们说在 cloudSenseData 我有 10 个目录项。

这些是我在按摩数据期间正在执行的步骤:

  1. 在 cloudSenseData 上使用 async.map 并将其映射到所需的响应格式。(我用它来使事情并行完成)并有一个回调函数来满足需要
  2. 在根据需要进行响应的同时在回调中检查它是否具有相关产品信息,如果没有问题,否则我正在调用下游端点以使用 catologueItemId 获取更多相关产品信息。(这里我使用的是 deasync )

这需要比需要更多的时间。

谁能建议任何替代方法来解决这个问题?

使用代码更新:common-nodejs 是我们编写的一个库,它包含许多功能,例如使用 restify 调用其余端点、读取应用程序配置等。下面的代码在 typescript 中。希望这可以帮助。

    import {log,serviceInfo,HttpMethod} from "common-nodejs";
    import { CloudsenseBaasJsonAction } from './cloudsense-baas-connector';
    import {Constants} from "./Constants";
    let request = require('request');
    let deasync = require('deasync');
    let moment = require("moment");
    let async= require("async");
    let PropertiesReader = require("properties-reader");
     let endpointsConfigFile = require("../../config/endpoints.json");
     //load the properties file to map the cloudsense attributes with        required keys.
     let parseConfig=new  PropertiesReader("config/fields_config.properties");

      // helper method  in adding more details in response by reading the properties file
     export let parsePropertiesFile =            function(attribute,microserviceResponse,key,value){
     let cloudSenseKey = attribute[key];
     let microServiceKey = parseConfig.get(cloudSenseKey);
     //console.log("********cloudSenseKey***************",cloudSenseKey,"************ microServiceKey***" ,microServiceKey);
     if( microServiceKey!= undefined && microServiceKey!=null){
    // console.log("********microServiceKey***************",microServiceKey  ,attribute[value]);
      microserviceResponse[microServiceKey] = attribute[value];
     }

     };
     // this method does the fetching the detailed info if relatedProducts are there
     export let requestRelatedProductsInfo = function(offerId):any{
     //  console.log("****************Above to Parse*******");
     let body={};
      let cloudsenseBaasJsonAction = new  CloudsenseBaasJsonAction(HttpMethod.GET, body, '');
      let sendRequestForRelatedProducts = deasync(function(callback){
       request({
         proxy: serviceInfo.extras.internetProxy,
        url:  serviceInfo.extras.serviceCloudsense.apiEndpoint+"/services/current/offer/"+offerId+"/products",
         method: endpointsConfigFile.cloudsense_baas.offers.method,
         headers: cloudsenseBaasJsonAction.modifyHeadersWithParams({
            "csTime": Date.now(),
            "method":   HttpMethod[endpointsConfigFile.cloudsense_baas.offers.method],
            "path": "/services/current/offer/"+offerId+"/products",
            "clientKey": serviceInfo.extras.serviceCloudsense.clientKey,
            "clientSecret":  serviceInfo.extras.serviceCloudsense.clientSecret
        })
    },function (err, res, body) {
        if(res.statusCode==404 || res.statusCode==500){
            console.log("********res***offerId*************",res.statusCode,offerId);
        }

        if(err){
            // console.log("*****************Errors****************",err);
            callback(err,null);
        }
        callback(null,body);
    });
});
return JSON.parse(sendRequestForRelatedProducts());
        }
       export class Parser {

/*
 * This method is used to massage the cloudsense data and respond with the below formate
 *
 * {
 *        "catalogueId": "a26O0000000SOS7IAO",
 *       "price": 1536,
 *        "name": "IPHONE 6S PLUS",
 *        "default": "true",
 *        "color": "Silver",
 *        "memory": "128GB",
 *        "contentId": "IPHONE6S128GBSILVER",
 *        "featured": "true",
 *        "isOutright": "Outright",
 *        "brand": "Apple",
 *        "startdate": "01-09-2016",
 *        "enddate": "01-09-2017",
 *        "OS": "iOS",
 *        "bluetick": true
 *    }
 *
 *
 */
public parseCloudsenseData(CloudsenseData:any,isDefaultFlow : boolean):any{
    console.log('*******isDefaultFlow********',isDefaultFlow);
    let current_Date = moment().format(Constants.DateFormate);
    let  parseCloudData = function(result,callback){
        try{
            let microserviceResponse={
                "catalogueId"      :    result.catalogueId,
                "catalogueItemId"  :   result.catalogueItemId,
                "outrightPrice"    :   result.cscfga__One_Off_Charge__c,
                "displayName"      :   result.name,
                "currentDate"      :   current_Date,
                "recurringPrice"   :   result.cscfga__Recurring_Charge__c
            };
            let key = Constants.Name;
            let value = Constants.Value;
            //fetch the list of attributes.
            for(let att of result.attributes){
                parsePropertiesFile(att,microserviceResponse,key,value);
            }
            debugger;
            //fetching the relatedProducts Data. if there are relatedProducts calling the endpoint to get more details 
            if(!isDefaultFlow && result.relatedProducts!= undefined && result.relatedProducts!=null  && result.relatedProducts.length>0 ){

                let microserviceRelatedProductArray=[];
              // debugger;
              //   result.catalogueItemId = 'caf71d86-bca3-4bed-a2d5-b233305b8e76'
                let relatedProductArray = requestRelatedProductsInfo(result.catalogueItemId);
                for(let relatedProduct of relatedProductArray.results){
                //     for(let relatedProduct of relatedProductArray){
                    let finalRelatedProduct ={
                        "productId"        :   relatedProduct.productId,
                        "name"             :   relatedProduct.name,
                        "sku"              :   relatedProduct.sku,
                        "productType"      :   relatedProduct.productType,
                        "productSubType"   :   relatedProduct.productSubType,
                        "outrightPrice"    :   relatedProduct.cscfga__One_Off_Charge__c,
                        "recurringPrice"   :   relatedProduct.cscfga__Recurring_Charge__c,
                        "contentId"        :   '',
                        "mobileRepaymnetOption":''
                    };
                    //This loop is there to find the content_id among available attributes dynamically.
                    for(let att of relatedProduct.attributes){
                        parsePropertiesFile(att,finalRelatedProduct,key,value);
                    }
                    microserviceRelatedProductArray.push(finalRelatedProduct);
                } // end of for loop.
                microserviceResponse.relatedProducts =microserviceRelatedProductArray;
            }//end of if. ( view details flow).
            // if(!isDefaultFlow && result.relatedProducts!= undefined && result.relatedProducts!=null  && result.relatedProducts.length>0 ) {
            // var catalogueItemIdArray = [];
            //     catalogueItemIdArray.push(result.catalogueId);
            // }
            return callback(null,microserviceResponse);
        }catch(error){
            // log.debug("************error block**********",error);
            return callback(error,null);
        }
    };

    let microServiceOutput;
    //calling the parseCloudData method asynchronusly for each element in the array.
    async.map(CloudsenseData.results, parseCloudData ,function (error,result){

        if(error){
            // console.log("***************Error***************",error);
            microServiceOutput = {
                "code":1005,
                "message": "The downstream is not available"
            };
            return microServiceOutput;
        }

        microServiceOutput = result;
    });



    return microServiceOutput;
}//End of parseCloudsenseData();

}

4

0 回答 0