The forEach is undefined in a Javascript Class Method - javascript

I are have a problem into my code. After many attempts in search for solutions I decided to get help from the stackoverflow community
I have created a Javascript Class for get registered members list. This members register is localized in to a Json file which system have access.
I'm trying to use an array data filter through forEach. But the method named: "Of(ChurchName)" don't read any foreach method into it. When I using into Of(), returns undefined.
Initially I used 'return' response in the method "createMemberList()", responsible to create the full array. This method it's working normally. But, using 'return' in a variable with ForEach method not work. Then, because this aparent error, I has used the 'this' operator instead of 'return'. But even so, as can you see in code, i can't use the forEach method at "createMemberList()".
Does anyone has any idea?
Details:
I aredy used that site tips:
https://www.techiedelight.com/copy-elements-array-into-another-array-javascript/
const $INIT = {
GetMembers: class{
#listaOrdenadaItens;
#listaMembros;
#MemberListOfChurch;
membersList;
#linkGFile="LinkToJsonFileHere";
/*Returns:
{
"range": "Membros!B5:AB234",
"majorDimension": "ROWS",
"values": [
[ "",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""]
]
}
*/
constructor(ListFromGD){
if(typeof ListFromGD!=="undefined"&&ListFromGD!==null){
this.#linkGFile=ListFromGD;
}
this.#createMemberList();
}
/*Members List*/
Of(ChurchName){
/**Filters member data according congregation
* Usage: new $INIT.GetMembers().Of("ChurchName")
*/
this.#MemberListOfChurch=[];;
this.ChurchName=ChurchName;
this.membersList.forEach((item, count) => {
console.log("Why this code don't appears in console?");
if (/^[a-zA-Z_À-Úà-ú\s]{2,50}$/.test(ChurchName)==true && ChurchName.toLocaleLowerCase() == item.congregacao.toLocaleLowerCase()) {
this.#MemberListOfChurch[count] = item;
}else{
console.log("Trys to check anyone error");
}
});
return this.#MemberListOfChurch;
}
#getListaOrdenada (){
return [
/**Personal Informations */
"Nome Completo",
"Sexo",
"CPF",
"Data de Nascimento",
"RG",
"Orgão Emissor",
"UF_RG",
"Data de Expedição",
"Estado Civil",
"CONJUGE",
"Naturalidade",
"UF_NAT",
"NOME_PAI",
"NOME_MAE",
/**Schooling and ecclesiastical data */
"GRAU_INSTRUCAO",
"PROFISSAO",
"FUNCAO_ECLESIASTICA",
"LOCAL",
"UF_BATISMO",
/**Address informations */
"Endereco",
"cep",
"bairro",
"cidade",
"uf",
"congregacao",
"contact_number",
"whatsapp_number"
]
}
#createMemberList(){
var listaOrdenada = this.#getListaOrdenada();
/**Create an array */
var NewListMember = [];
var DadosMembros={};
/**
* Gets registered members list at system!
*/
this.#getJSON(this.#linkGFile).then(response=>{
response.values.forEach((item, i)=>{
/**Examina membro por membro aqui */
if(item[0]===undefined)return;
/**Creates a name for array of values: Ex: {"Complete Name" : "Leonardo Lima de Sousa"} */
listaOrdenada.forEach((ItemName,N)=>{
if(ItemName===undefined) return;
DadosMembros[ItemName]=item[N];
});
NewListMember[i] = DadosMembros;
DadosMembros={};
});
})
this.membersList=NewListMember;
}
#getJSON=async t=>{const r=await fetch(t);if(!r.ok)throw new Error(r.statusText);return r.json()};
}
}
If I run this code of this function directly in the Chrome Console, it's works. But in this Class Method, returns undefined

const newArr = [...arr1, ...arr2] will copy all the elements from arr1 and arr2 to newArr. You don't need to use foreach.

TEMPORARY SOLUTION
A temporary solution for this problem is copy CreateMemberList() content to Of() Method. Thereafter, It's necessary create a new Array named NewListMember[] and apply congregations data via objects to it where congregation name is equal ChurchName param
The Of() Method will be staying this:
Of(ChurchName){
/**Filters member data according congregation
* Usage: new $INIT.GetMembers().Of("ChurchName")
*/
var
listaOrdenada = this.#getListaOrdenada(),
NewListMember = [],
newArray = [],
DadosMembros = {};
/**
* Gets all registered members data by Json array.
*/
this.#getJSON(this.#linkGFile).then(response=>{
//Creates a counter variable
var newI=0;
response.values.forEach((item, i)=>{
/**examines member by member here */
if(item[0]===undefined)return;
/**Creates a property name for this array value: }
*Ex: {"Nome completo" : "Leonardo Lima de Sousa"}
* "Complete Name"
*/
listaOrdenada.forEach((ItemName,N)=>{
if(ItemName===undefined) return;
DadosMembros[ItemName]=item[N];
});
//Gets current congregation name and set all letters to lowerCase()
var ThisCongregation = DadosMembros.congregacao;ThisCongregation=ThisCongregation.toLowerCase();
//Gets congregation name in to param: ChurchName and set all letters to lowerCase()
var CongregationIndicate = ChurchName.toLowerCase();
//Gets Congregation where Congregation name is equal Param ChurchName
////Then, creates a new size for array NewListMember with newI counter
if(ThisCongregation!==undefined&&ThisCongregation!==CongregationIndicate)return;
NewListMember[newI] = DadosMembros;
++newI;
DadosMembros={};
});
});
return NewListMember
}

DEFINITIVE SOLUTION
where were problem?
What's solution?
The #createMemberList() generate an array with more than 220 rows. Then, it's necessary wait a while for Of() method to process everything.
For it, it's must to use setTimeout() function in the method, like this:
setTimeout(()=>{
console.log(JSON.stringify(this.membersList))
},3000)
The code will to stay like this:
const $INIT = {
GetMembers: class{
#listaOrdenadaItens;
#listaMembros;
#MemberListOfChurch;
membersList;
#linkGFile="https://cdn.jsdelivr.net/gh/OficialLeonardoLima/cdn#main/json_test.json";
constructor(ListFromGD){
if(typeof ListFromGD!=="undefined"&&ListFromGD!==null){
this.#linkGFile=ListFromGD;
}
this.#createMemberList();
setTimeout(()=>{
console.log(JSON.stringify(this.membersList))
},3000)
document.querySelector("#console").text=JSON.stringify(this.membersList)
}
/*Members List*/
Of(ChurchName){
/**Filters member data according congregation
* Usage: new $INIT.GetMembers().Of("ChurchName")
*/
this.#MemberListOfChurch=[];;
this.ChurchName=ChurchName;
setTimeout(()=>{
this.membersList.forEach((item, count) => {
console.log("Why this code don't appears in console?");
if (/^[a-zA-Z_À-Úà-ú\s]{2,50}$/.test(ChurchName)==true && ChurchName.toLocaleLowerCase() == item.congregacao.toLocaleLowerCase()) {
this.#MemberListOfChurch[count] = item;
}else{
console.log("Trys to check anyone error");
}
});
},3000);
return this.#MemberListOfChurch;
}
#getListaOrdenada (){
return [
/**Personal Informations */
"Nome Completo",
"Sexo",
"CPF",
"Data de Nascimento",
"RG",
"Orgão Emissor",
"UF_RG",
"Data de Expedição",
"Estado Civil",
"CONJUGE",
"Naturalidade",
"UF_NAT",
"NOME_PAI",
"NOME_MAE",
/**Schooling and ecclesiastical data */
"GRAU_INSTRUCAO",
"PROFISSAO",
"FUNCAO_ECLESIASTICA",
"LOCAL",
"UF_BATISMO",
/**Address informations */
"Endereco",
"cep",
"bairro",
"cidade",
"uf",
"congregacao",
"contact_number",
"whatsapp_number"
]
}
#createMemberList(){
var listaOrdenada = this.#getListaOrdenada();
/**Create an array */
var NewListMember = [];
var DadosMembros={};
/**
* Gets registered members list at system!
*/
this.#getJSON(this.#linkGFile).then(response=>{
response.values.forEach((item, i)=>{
/**Examina membro por membro aqui */
if(item[0]===undefined)return;
/**Creates a name for array of values: Ex: {"Complete Name" : "Leonardo Lima de Sousa"} */
listaOrdenada.forEach((ItemName,N)=>{
if(ItemName===undefined) return;
DadosMembros[ItemName]=item[N];
});
NewListMember[i] = DadosMembros;
DadosMembros={};
});
})
this.membersList=NewListMember;
}
#getJSON=async t=>{const r=await fetch(t);if(!r.ok)throw new Error(r.statusText);return r.json()};
}
}

Related

how to create multiple things saved in local storage

I have some code which allows me to get data from the user and gets saved locally but doesn't make a new item in local storage for each set of inputs.
It currently save s the data but only until you delete it or overwrites it
How do I make it so it creates a new storage item rather than overwriting it?
let reminders = [];
const addReminders = (ev) => {
ev.preventDefault();
let reminder = {
ReminderInput: document.getElementById('ReminderInput').value,
DateInput: document.getElementById('DateInput').value,
InfoInput: document.getElementById('InfoInput').value
}
const arr = [reminder.ReminderInput, reminder.DateInput, reminder.InfoInput]
localStorage.setItem('todoForm', JSON.stringify(arr))
localStorage.getItem('todoForm', JSON.parse(arr))
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addReminders);
});
<div class="container">
<!-- The above form looks like this -->
<div class="row">
<div class="six columns" style="margin-top: 20%">
<form id="todoForm">
<label for="ReminderInput">Reminder</label>
<input class="u-full-width" type="text" id="ReminderInput">
<label for="DateInput">Date</label>
<input class="u-full-width" type="datetime-local" id="DateInput">
<label for="InfoInput">Additional Information</label>
<textarea class="u-full-width" type="text" placeholder="Remember to..." id="InfoInput"></textarea>
<button type="button" id="btn" class="button-primary">Add Reminder</button>
</form>
</div>
</div>
</div>
In localstorage, the items are identified by their names. If you save two different objects with the same name, the last one will overwrite the first, as you've seen.
In this circumstance, it may be better to keep a list of all the reminders (or get it from the localstorage), add the new one to the list and save the whole list.
let reminders = JSON.parse(localStorage.getItem("reminders"));
// ...
reminders.push([reminder.ReminderInput, reminder.DateInput, reminder.InfoInput]);
localStorage.setItem("reminders", JSON.stringify(reminders));
You should store the object inside the array:
// getItem will return a string, so you have to parse in this way:
const storedJson = localStorage.getItem('todoForm');
const reminders = storedJson ? JSON.parse(storedJson) || [];
// into the array you should store object, not single data:
function addReminders(ev) {
ev.preventDefault();
const reminder = {
ReminderInput: document.getElementById('ReminderInput').value,
DateInput: document.getElementById('DateInput').value,
InfoInput: document.getElementById('InfoInput').value
};
reminders.push(reminder);
updateStorage();
}
function updateStorage() {
localStorage.setItem("reminders", JSON.stringify(reminders));
}
In this way the data will be more clear and you'll have an easier access to it.
Here is whole example you just need to oranize your data as you well.
Important this example dont work on code snippet becouse :
Failed to read the 'localStorage' property from 'Window': The
document is sandboxed and lacks the 'allow-same-origin' flag.
Test on : codepenio
/**
* LocalStorageMemory save and load js objects in localStorage.
*/
var localStorageMemory = {
localStorage: window.localStorage,
/**
* save Put the object into storage.
* #example Usage : save("MyObjectKey", myObject )
* #method save
* #param {String} Name Name of localstorage key
* #param {object} Value Any object we can store.
* #return {false | object} What ever we are stored intro localStorage.
*/
save: function(name, obj) {
try {
return localStorage.setItem(name, JSON.stringify(obj));
} catch (e) {
console.log("Something wrong in LocalStorageMemory class , method save! -> ", e);
return false;
}
},
/**
* Load saved object from storage. Retrieve the object from storage or
* return false.
* #example Usage : var giveMeMyObject = load("MyObjectKey")
* #function load
* #param {String} Name Name of localstorage key
* #return {false | object} What ever we are stored intro localStorage.
*/
load: function(name) {
if (localStorage.getItem(name) === "undefined" || localStorage.getItem(name) == null || localStorage.getItem(name) === "") {
console.warn("LocalStorageMemory method load return's: ", localStorage.getItem(name));
return false;
} else {
return JSON.parse(localStorage.getItem(name));
}
}
}
/**********CREATE INSTANCE***********/
var saveAnyDataObj = {
name: "wins",
numberOfWins: c++
};
localStorageMemory.save("MyObject1", saveAnyDataObj);
var getMyMemory = localStorageMemory.load("MyObject1");
console.log("MyObject1 = ", getMyMemory);
var c = 0;
setInterval(function() {
var saveAnyDataObj = {
name: "wins",
numberOfWins: c++
};
localStorageMemory.save("MyObject1", saveAnyDataObj);
getMyMemory = localStorageMemory.load("MyObject1");
document.getElementById("result").innerHTML = getMyMemory.numberOfWins;
}, 1000);
Do something like this :
let reminders = [];
let arr;
const addReminders = (ev) => {
ev.preventDefault();
let reminder = {
ReminderInput: document.getElementById('ReminderInput').value,
DateInput: document.getElementById('DateInput').value,
InfoInput: document.getElementById('InfoInput').value
}
if(localStorage.getItem("todoForm") === null){ //check if localstorage is empty
arr=[];
}else{
arr = JSON.parse(localStorage.getItem("todoForm");
//if it already has elements,it will set 'arr' to the elements of localStorage
})
arr.push(reminder.ReminderInput, reminder.DateInput, reminder.InfoInput); //push your new elements
localStorage.setItem('todoForm', JSON.stringify(arr))
localStorage.getItem('todoForm', JSON.parse(arr))
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addReminders);
}
For example if ur local storage consists of a array like this:
['todo1','todo2','todo3']; //array 1
when you are setting the localStorage with new todo items like
['todo4','todo5']
The previous wont get replaced because."array1" will be retrived to 'arr'.like this
arr = ['todo1','todo2','todo3']; //from localStorage;
later you push your new elements 'todo4','todo5';
the arr becomes
arr = ['todo1','todo2','todo3','todo4','todo5'];
It is basically retriving the elements from localStorage to an array and adding new elements to the array and set localStorage with the modified array,like this you wont overwrite your existing elements

How to run a function for each item in an array or write array objects individually on Mongoose

Hi everyone I'm trying to create an API for calculating revenue from a calculator service, all it essentially does is grab the values from the dB that the calculator needs and pass them through it and get the resulting values. I need to write the results back into the dB however for logging.
I'm having some problems however
I am trying to pass some objects from a Mongoose array to a JSON API URL service using axios get and I'm having trouble writing the resulting array to my Mongoose dB
Can anyone help me with what I'm missing?
See below
/* Users :
_id : 5cac
username: sample
email: email#email.com
orderHistory: [
{xmr_hr: 9000},
{xmr_hr: 2000},
{xmr_hr: 3000}
],
profitHistory:[
{
xmr_usd_gross:
}
]
*/
var email = "email#email.com"
var id = "5cac"
function xmr(callback){
function getUsers(){
var cursor = User.find({email: email}, function (err, users) {
}).cursor();
return cursor;
}
var cursor = getUsers();
cursor.on('data', function(name){
const xmr_hr= name.orderHistory.map(element => element.xmr_hr);
var xmrLength = xmr_hr.length;
for (var i = 0; i < xmrLength; i++) {
console.log(xmr_hr[i]
// returns [9000,2000,3000]
// variables
var algo = "cn8"
var hr = xmr_hr
var wttURL = "wtt.com/json" + algo + hr[i]
axios.get(wttURL)
.then((response) => {
var btcGrossRevenue = response.data.coins.Monero.btc_revenue
console.log(btcGrossRevenue)
// runs through each value in array and returns revenue [0.06, 0.02, 0.03]
// below is my problem
var updateProfits = [{
xmr_usd_gross : btcGrossRevenue,
}]
User.findByIdAndUpdate(id, {upsert: false, "$addToSet": { 'profitHistory': updateProfits}},
function(err, user) {
if(err) { console.log(err) }
else {
console.log(user.length)
};
})
})
}
// initial callback
for (var v = 1; v < 2; v++)
xmr(function(v){})
// cronJob and callback continuation
var xmrJob = new cron.CronJob('* 10 * * * *', function() {
console.log('Function executed!');
for (var v = 1; v < 2; v++) // amount of times to run function
xmr(function(v){})
}, null, true);
xmrJob.start
I know the problem is the fact that I'm trying to write an array to an object inside an array, but I'm not sure how to pass each object in the array individually.
I am thinking either there is a way to do it by just running the callback function individually for each object item in the array or find the ability to dissect the resulting array and write them sequentially.
I would like for my Collections to look like this once everything is written
/* Users :
_id : 5cac
username: sample
email: email#email.com
orderHistory: [
{xmr_hr: 9000},
{xmr_hr: 2000},
{xmr_hr: 3000}
],
profitHistory:[
{xmr_usd_gross: 0.06},
{xmr_usd_gross: 0.03},
{xmr_usd_gross: 0.02},
]
*/
Any help would be much appreciated
You can use the Map function.
const fn = (item) => {
return item *10;
}
[1,2,3,4,5].map( fn );
with this simple example, the function fn is executed on each item in the map and returns a value. If you assign it to something you can leverage that value resulting array.
I obviously seperated them out but you can easily do them inline as well.... or leverage the forEach function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[1,2,3,4,5].map( item => item * 10 );
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
[1,2,3,4,5].forEach( item => {
console.log( item * 10 );
});
Your arrays can be anything, objects, numbers whatever, and similarly... you can do anything in the functions.

How to use Loop to execute store procedure in Cosmos-DB/Document-DB?

I have JSON like
{
"id": "58d99ca3231f13b9ecbbbca4",
"50records": [
{
"aomsLineNbr": 1,
"licenses": [
{
"productKey": "84fc2cde-9735-4cea-b97a-3cd627d3d0a5",
"aid": "someAid"
}
]
}
]
}
I want to fetch record on the basis of aid.
50record can have multiple objects and licenses can also have multiple objects.
I am constucting the query as
"SELECT * FROM orders o WHERE o['50records'][0].licenses[0].aid='someAid'"
how can I loop those 50records and licenses to search aid in all available objects?
Below is my store procedure:
function getOrdersByAidCollection(aid){
var context = getContext();
var collection = context.getCollection();
var link = collection.getSelfLink();
var response = context.getResponse();
var query = "SELECT * FROM orders o WHERE o['50records'][0].licenses[0].aid='"+aid+"'";
var isAccepted = collection.queryDocuments(collection.getSelfLink(),query,
function (err, feed, options) {
if (err) {
return errorResponse(400, err.message);
}
if (!feed || !feed.length){
return errorResponse(400, "no orders doc found");
}else {
getContext().getResponse().setBody(JSON.stringify(feed));
}
});
if (!isAccepted){
return errorResponse(400, "The query was not accepted by the server.");
}
}
Where and how I need to put a loop ??
Any help will be appreciable!
Thanks
why do you need a loop? This looks like a query question. Can you try a query like this:
SELECT VALUE r
FROM orders c
JOIN r in c["50records"]
JOIN li in r.licenses
WHERE li.aid = "someAid"
Thanks!

0 Results Returned from NetSuite Search

I am attempting to stop a record from being created based on a search result. I can't seem to return any data through my SuiteScript search though, even though I know for a fact the data exists.
I created a Custom Saved Search with the exact filter being used below and return the results I am looking for.
Does anything stand out on why I may not be retrieving any results?
NOTE: The sfdcAccountId Variable does have a value, so I am searching on a valid value.
// 2.0
define(["N/error", "N/log", "N/search"], function (err, log, search) {
/**
* User Event 2.0 example showing usage of the Submit events
*
* #NApiVersion 2.x
* #NModuleScope SameAccount
* #NScriptType UserEventScript
* #appliedtorecord customer
*/
var exports = {};
function beforeSubmit(scriptContext) {
log.debug({
"title": "Before Submit",
"details": "action=" + scriptContext.type
});
if (doesCustomerExist(scriptContext)) {
throw err.create({
"name": "DUPLICATE_SFDC_ACCOUNT_ID",
"message": "Customer Already Contains SFDC Account Id",
"notifyOff": true
});
}
}
function doesCustomerExist(scriptContext) {
var sfdcAccountId = scriptContext.newRecord.getValue('custentitysfdc_account_id');
log.debug({
"title": "Before Submit",
"details": "sfdcAccountId=" + sfdcAccountId
});
if(sfdcAccountId == null || sfdcAccountId == '') return false;
var searchResult = search.create({
type: search.Type.CUSTOMER,
filters: ['custentitysfdc_account_id', search.Operator.IS, sfdcAccountId]
}).run();
return (searchResult != null && searchResult.length > 0);
}
exports.beforeSubmit = beforeSubmit;
return exports;
});
When you call .run() on a search, it returns a search.ResultSet object. If you call getRange() on that object, you'll get the array of results that you're looking for. Here's an updated version of your search that returns search.Result[] on which you can check the length or iterate through as necessary.
var searchResult = search.create({
type: search.Type.CUSTOMER,
filters: ['custentitysfdc_account_id', search.Operator.IS, sfdcAccountId]
}).run().getRange({start: 0, end: 1000});

How to approach this scenario in async programming /node js

I am writing a service in nodejs. Please read below for the approach i am doing to solve this problem.
First I call a rest endpoint(say /offers) to fetch data . say it cloudSenseData
Final Response I need to massage/manipulate the data to give back the needed response as output.
During massaging the data(from above call) I have to check if there is a relatedProduct info present.
if present I need to call another rest endpoint(say /offers/:id/products)
the :id is catalogueitemid obtained in previous call(cloudSenseData) to get more relatedProduct info details which i can include in the final massaged output.
So lets say in cloudSenseData I have 10 catalogueItems.
These are the steps i am doing during massaging the data:
Using async.map on cloudSenseData and mapping it to the needed response format.(I used it to make things parallel done)and have a callback function doing the need
In the callback apart while making the response as needed I am checking if it has relatedProduct info
if it doesnt have no issue
else i am calling downstream endpoint to get more relatedProductInfo using catologueItemId.(here i am using deasync )
This is taking more time than needed.
Can anyone please suggest any alternatives to approach this?
Update with Code : common-nodejs is a library we have written that wraps many functionalities like calling the rest endpoints using restify, reading the app configuration and many such. The below code is in typescript .
Hope this helps.
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();
}

Categories

Resources