I have used node.js and request.js to access form information from our email services API. With the console.log in the function I am able to see all the info that I need. I have tried to access it outside of the function with dot notation(request.missionStatement) which I don't think is right. I want to be able to display this on a page within an express.js app.
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
console.log(missionStatement)
}
);
The variable missionStatement is a local variable declared inside an anonymous function passed as an argument to the request function, and thus it is inaccessible once the anonymous function returns. You must save your result elsewhere. Try something like this:
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
var result;
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
result = missionStatement;
displayResult();
});
function displayResult() {
console.log(result);
}
Your missionStatement will now be saved in result, but only after the anonymous callback to request() has been called (when the actual request is finished).
Related
Passing variables within the functions : I want to pass mentioned variable (insTypeDB) to another function. Please see the image.
//Getting Symbol details from DB API
var insTypeDB;
pm.sendRequest("http://192.168.14.116:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response) {
var resBoday = response.json()
insTypeDB = resBoday.items[0].instrument_type_id;
//var intInsTypeDB = parseInt(insTypeDB);
console.log("insTypeDB " + insTypeDB);
//pm.expect(insTypeDB).is.to.equals(2);
});
//Verify Instrument Type with DB API
pm.test("Row : " + i + " - " + dataArr[1] + " : Verify symbol Instrument type with DB", function () {
let insTypeRes = dataArr[2];
let intInsType = parseInt(insTypeRes);
console.log("insType " + intInsType);
pm.expect(insTypeDB).is.to.equals(intInsType);
});[enter image description here][1]
Passing Variables error
//Getting Symbol details from DB API
var insTypeDB;
pm.sendRequest("http://192.168.14.116:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response) {
var resBoday = response.json()
insTypeDB = resBoday.items[0].instrument_type_id;
//var intInsTypeDB = parseInt(insTypeDB);
console.log("insTypeDB " + insTypeDB);
//pm.expect(insTypeDB).is.to.equals(2);
//Verify Instrument Type with DB API
pm.test("Row : " + i + " - " + dataArr[1] + " : Verify symbol Instrument type with DB", function () {
let insTypeRes = dataArr[2];
let intInsType = parseInt(insTypeRes);
console.log("insType " + intInsType);
pm.expect(insTypeDB).is.to.equals(intInsType);
});[enter image description here][1]
});
add the test inside the sendRequest as it is a call back else use setTimeOut which will wait for the value to be populated
pm.sendRequest("http://192.168.14.116:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response) {
var resBoday = response.json()
insTypeDB = resBoday.items[0].instrument_type_id;
//var intInsTypeDB = parseInt(insTypeDB);
console.log("insTypeDB " + insTypeDB);
pm.varaible.set("insTypeDB",insTypeDB);
});
setTimeout(()=>{
pm.test("Row : " + i + " - " + dataArr[1] + " : Verify symbol Instrument type with DB", function () {
let insTypeRes = dataArr[2];
let intInsType = parseInt(insTypeRes);
console.log("insType " + intInsType);
pm.expect(pm.varaible.get("insTypeDB")).is.to.equals(intInsType);
})
},5000)
I have written a script function to get google sheet data and send the email as an attached PDF. I have used here pivot tables in the google sheet.
The problem is here. after the filtered pivot table and then if I send an email.it sent only without filter data. That means is default values only export as pdf.
How to send an email pdf with current filtered data?
function sendEmail(){
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var getTabsheetName=ss.getSheetByName('report');
var url = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/'
+ ss.getId() //Your File ID
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=LETTER'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.50'
+ '&bottom_margin=0.50'
+ '&left_margin=0.50'
+ '&right_margin=0.50'
+ '&sheetnames=false&printtitle=false&pagenumbers=true'
+ '&pagenum=false'
+ '&gridlines=false'
+ '&fzr=FALSE'
+ '&gid='
+ getTabsheetName.getSheetId(); //the sheet's Id
var emailsheet=ss.getSheetByName('Email');
var emailContentsheet=ss.getSheetByName('EmailContent');
var subject = emailContentsheet.getRange(2,1).getValue();
var n=emailsheet.getLastRow();
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob().setName('Report.pdf');
for (var i = 2; i < n+1 ; i++ ) {
// SpreadsheetApp.flush();
var emailAddress = emailsheet.getRange(i,2).getValue();
var name=emailsheet.getRange(i,1).getValue();
var message = emailContentsheet.getRange(2,2).getValue();
var returnData = [name,message];
var templ = HtmlService.createTemplateFromFile('index');
templ.data = returnData;
var htmlboday = templ.evaluate().getContent();
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: htmlboday,
attachments:[blob]
});
}
} catch (f) {
Logger.log(f.toString());
}
}
I need help to get a value of a json for a function and pass this value of the function to the console, but now i'm recive var = undefined, follow the code below, thanks
var Site = {
baseUrl: "https://www.usereserva.com/",
visitUrl: "https://cloud-commerce-visit.oracleoutsourcing.com/"
}
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId;
var prodId = '0058597';
console.log("============= SCRIPT CALLCAPRODUCT ==============");
console.log("url API: " + prodAPI);
console.log("Id buscada: " + prodId);
var request = require('request');
var price;
function prodPrice() {
request(Site.baseUrl + "ccstoreui/v1/prices/" + prodId, function (error, response, body) {
var corpo = JSON.parse(body);
price = corpo['sale'];
console.log(price); // result 169
});
}
console.log("preço: " + prodPrice());
console.log("Requisição CALLPRODUCT foi bem sucedida");
console.log("================================================");
Yes, you are using prodId variable before assigning the value to prodId. This will return error. Here hoisting will take place. Your code will be compiled as
var Site = {
baseUrl: "https://www.usereserva.com/",
visitUrl: "https://cloud-commerce-visit.oracleoutsourcing.com/"
}
var prodId ;
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId; // so here
// prodId is undefined,thats why error.
prodId = '0058597';
console.log("============= SCRIPT CALLCAPRODUCT ==============");
console.log("url API: " + prodAPI);
console.log("Id buscada: " + prodId);
var request = require('request');
var price;
function prodPrice() {
request(Site.baseUrl + "ccstoreui/v1/prices/" + prodId, function (error, response, body) {
var corpo = JSON.parse(body);
price = corpo['sale'];
console.log(price); // result 169
});
}
console.log("preço: " + prodPrice());
console.log("Requisição CALLPRODUCT foi bem sucedida");
console.log("================================================");
initialize and assign the prodId variable first and then use it
var prodId = "0058597";
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId;
Another one is that you are not returning any value from prodPrice() method and default return is undefined.
return the required value from method.
Please read about hoisting in java script. this will help Hoisting
Use Let or const instead of var to avoid such problems.
https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75
I am writing a function calling an API to fetch URLs. These are the steps that I wish to accomplish:
Parsing in an array of objects (restaurants) as arguments
For each object, call the Google Search API to get some imageURLs
Store those imageURLs in an array
Add imageURLs as an attribute called imageURLs to each object within the array in the argument
The code is able to log the imageURLs within the GET request, but outside of the request, imageURLs is just an empty array.
var googleSearch = function(restaurants, cb){
console.log("google starts");
const apiKey = google_apiKey;
const cseKey = cseID;
Array.from(restaurants).forEach(function(restaurant){
var keyWord = restaurant.name + " "+ restaurant.location.city
+ " "+ restaurant.location.state + " food";
var googleURL = "https://www.googleapis.com/customsearch/v1?key="+ apiKey +
"&q="+ keyWord +
"&searchType=image" +
"&cx=" + cseKey +
"&num=7" +
"&safe=medium"
;
//image URLs of each restaurants to be displayed in the front end
var imageURLs = [];
request
.get(googleURL,
{
json : true, headers: {
'User-Agent' : 'thaorell'
}
})
.then(function(response){
Array.from(response.items).forEach(function(item){
imageURLs.push(item.link)
});
})
.catch(e => {
console.log(e);
})
restaurant.imageURLs = imageURLs
})
cb(null, restaurants);
}
You're misunderstanding the Promise API:
var googleSearch = function (restaurants, cb) {
console.log("google starts");
const apiKey = google_apiKey;
const cseKey = cseID;
return Promise.all(Array.from(restaurants).map(function (restaurant) {
var keyWord = restaurant.name + " " + restaurant.location.city
+ " " + restaurant.location.state + " food";
var googleURL = "https://www.googleapis.com/customsearch/v1?key=" + apiKey +
"&q=" + keyWord +
"&searchType=image" +
"&cx=" + cseKey +
"&num=7" +
"&safe=medium"
;
return request
.get(googleURL,
{
json: true, headers: {
'User-Agent': 'thaorell'
}
}
)
.then(function (response) {
restaurant.imageURLs = Array.from(response.items).map(function (item) {
return item.link;
});
return restaurant;
})
})
)
.then(restaurants2 => cb(null, restaurants2))
.catch(cb)
}
As you can see you need to wait for all of the requests to finish before you pass the data back to the callback.
I am trying to find out all the records that matches a user from a Parse class (namely, UserBeaconTracking). I am able to get correct user object and beacon object to begin with. However, when I use the statement
userBeaconTrackingQuery.equalTo("user", user);
Returned Error 102 with an error message "value is expected instead of map type."
What is it that I am doing wrong?
Here is the code snippet:
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("username", username);
userQuery.find().then(function(currentUser) { // get the user who sent the request
user = currentUser;
console.log("User" + JSON.stringify(user) + "Beacon Name :: " + JSON.stringify(visitedBeaconName));
}).then(function () { // get the beacons with which user communicated
var beaconRelation = Parse.Object.extend("Beacon");
var beaconQuery = new Parse.Query(beaconRelation);
beaconQuery.equalTo("name", visitedBeaconName);
return beaconQuery.find();
}).then(function (beacons) { // get user beacon transaction details
console.log("number of beacons " + beacons.length + " " + beacons[0]);
visitedBeacon = beacons[0];
console.log("beacon :: " + visitedBeacon);
var userBeaconTracking = Parse.Object.extend("UserBeaconTracking");
var userBeaconTrackingQuery = new Parse.Query(userBeaconTracking);
userBeaconTrackingQuery.equalTo("user", user);
userBeaconTrackingQuery.equalTo("beacon", visitedBeacon);
userBeaconTrackingQuery.find({
success : function (results) {
visitCounter = results[0].get("count");
console.log ("Visit Counter :: " + visitCounter);
// get the list of stores associated with the beacon
var beaconTable = Parse.Object.extend("Beacon");
var brandsAssociatedWithBeacon = new Parse.Query(beaconTable);
brandsAssociatedWithBeacon.get(visitedBeacon.id).then(function(beacon) {
typeOfBeacon = beacon.get("type");
console.log("Beacon Type ::" + typeOfBeacon);
var beaconBrandRelation = beacon.relation("brand");
var query = beaconBrandRelation.query();
//return query.find();
});
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
});