Parse Cloud Code : Doing a httpRequest within another httpRequest - javascript

I'm trying to do a httpRequest within another. I'll explain what I'm doing.
I am retrieving some datas from a Parse table (GET request) and, if this request succeed, I want to to another GET request to another Parse table, and unfortunately my second http Request didn't work at all, it didn't even finish as success or error.
This is what I have until now.
function getUserInformations(deviceId)
{
var response = new Parse.Promise();
var userInfos;
var apiKey = <<API Key>>;
var url = "http://api.timezonedb.com/?zone=";
Parse.Cloud.httpRequest({
method: "GET",
url: "https://api.parse.com/1/classes/User",
headers: {
"X-Parse-Application-Id": <<Application Id>>,
"X-Parse-REST-API-Key": <<REST API Key>>,
"Content-Type": "application/json"
},
success: function(httpResponse) {
var jsonObject = JSON.parse(httpResponse.text);
var x;
var count = 0;
for (x in jsonObject.results)
{
if (jsonObject.results.hasOwnProperty(x))
count++;
}
for (x = 0; x < count; x++)
{
if (jsonObject.results[x].deviceId == deviceId)
break;
}
if (x < count && jsonObject.results[x].deviceId == deviceId)
{
userInfos.email = jsonObject.results[x].email;
userInfos.name = jsonObject.results[x].name;
}
url += userInfos.timeZone;
url += "&format=json&key=";
url += apiKey;
Parse.Cloud.httpRequest({
method: "GET",
url: url,
headers: {
"Content-Type":"application/json"
},
success: function(httpResponse) {
var timestamp = httpResponse.data.timestamp;
var date = new Date(timestamp * 1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var time = hours + minutes.substr(-2);
},
error: function(httpResponse) {
}
});
response.resolve(userInfos);
},
error: function(httpResponse) {
response.reject(userInfos);
}
});
return (response);
}
Any idea ?

Related

Google Script - if error, return null and move to next row

Currently the script works totally fine but has one issue, every time there is an error, it stops, then I have to delete that row with error and run the script again.
What I want is, if there is an error then it should return the results as null and then move to next line item, so that there is no manual interruption.
function getSearchAnalytics(){
var service = getService();
if (service.hasAccess()) {
for(var i=7;i<525;i++){
var site = s_searchAnalytics.getRange(i, 1).getValue();
if (!site){
continue;
return null
}
var apiURL = 'https://www.googleapis.com/webmasters/v3/sites/' + URLDecode(site) + '/searchAnalytics/query?fields=rows&alt=json';
var lastRow = s_searchAnalytics.getLastRow();
s_searchAnalytics.getRange(i,2,lastRow,5).clear();
var headers = {"Authorization": "Bearer " + getService().getAccessToken()};
var payload = {
"startDate" : startDate,
"endDate" : endDate,
"dimensions" : ["device"],
"rowLimit" : "25000"
};
var options = {
"headers": headers,
"contentType":'application/json',
"method" : "post",
"payload" : JSON.stringify(payload),
"muteHttpExceptions": true
};
try {
var response = UrlFetchApp.fetch(apiURL, options);
}
catch (e) {
Logger.log(e);
}
Logger.log(response)
if (!response){
continue;
return null
}
var result = JSON.parse(response.getContentText());
if (result.error){
Browser.msgBox(result.error.errors[0].message);
return null
}
var row = []
for (var k in result.rows){
row.push([
result.rows[k].keys[0],
result.rows[k].metric1,
result.rows[k].metric2,
result.rows[k].metric3,
result.rows[k].position
]);
}
s_searchAnalytics.getRange(i,2,row.length,5).setValues(row);
}} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
}
}
I tried to replicate your code and found some issues:
Using return statement in your loop with terminate the whole function. Instead, use only continue. In line 9 and 47: the code will never reach the return null because you already use continue. Continue will leave the current iteration and move to the next one.
Instead of using if(!response), It would be easier to determine if the API call has an error by identifying the response code.
Informational responses (100–199)
Successful responses (200–299)
Redirects (300–399)
Client errors (400–499)
Server errors (500–599)
By using the response code, we can prevent writes if the response code is not 200(OK).
Here I modified your code:
function getSearchAnalytics() {
var service = getService();
if (service.hasAccess()) {
for (var i = 7; i < 525; i++) {
var site = s_searchAnalytics.getRange(i, 1).getValue();
if (!site) {
continue;
}else{
var apiURL = 'https://www.googleapis.com/webmasters/v3/sites/' + URLDecode(site) + '/searchAnalytics/query?fields=rows&alt=json';
var startDate = Utilities.formatDate(s_searchAnalytics.getRange(2, 2).getValue(), "GMT+7", "yyyy-MM-dd");
var endDate = Utilities.formatDate(s_searchAnalytics.getRange(3, 2).getValue(), "GMT+7", "yyyy-MM-dd");
var lastRow = s_searchAnalytics.getLastRow();
s_searchAnalytics.getRange(i, 2, lastRow, 5).clear();
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var payload = {
"startDate": startDate,
"endDate": endDate,
"dimensions": ["device"],
"rowLimit": "25000"
};
var options = {
"headers": headers,
"contentType": 'application/json',
"method": "post",
"payload": JSON.stringify(payload),
"muteHttpExceptions": true
};
try {
var response = UrlFetchApp.fetch(apiURL, options);
} catch (e) {
Logger.log(e);
}
Logger.log(response)
if (response.getResponseCode() == 200) {
var result = JSON.parse(response.getContentText());
var row = []
for (var k in result.rows) {
row.push([
result.rows[k].keys[0],
result.rows[k].clicks,
result.rows[k].impressions,
result.rows[k].ctr,
result.rows[k].position
]);
}
s_searchAnalytics.getRange(i, 2, row.length, 5).setValues(row);
}
}
}
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
}
}
Reference:
HTTP response status code
I took ideas from both your codes and it worked. Here is the final version that's working.
function getSearchAnalytics(){
var service = getService();
if (service.hasAccess()) {
for(var i=7;i<525;i++){
var site = s_searchAnalytics.getRange(i, 1).getValue();
if (!site){
continue;
return null
}
var apiURL = 'https://www.googleapis.com/webmasters/v3/sites/' + URLDecode(site) + '/searchAnalytics/query?fields=rows&alt=json';
var startDate = Utilities.formatDate(s_searchAnalytics.getRange(2, 2).getValue(), "GMT+7", "yyyy-MM-dd");
var endDate = Utilities.formatDate(s_searchAnalytics.getRange(3, 2).getValue(), "GMT+7", "yyyy-MM-dd");
var lastRow = s_searchAnalytics.getLastRow();
s_searchAnalytics.getRange(i,2,lastRow,5).clear();
var headers = {"Authorization": "Bearer " + getService().getAccessToken()};
var payload = {
"startDate" : startDate,
"endDate" : endDate,
"dimensions" : ["device"],
"rowLimit" : "25000"
};
var options = {
"headers": headers,
"contentType":'application/json',
"method" : "post",
"payload" : JSON.stringify(payload),
"muteHttpExceptions": true
};
try {
var response = UrlFetchApp.fetch(apiURL, options);
}
catch (e) {
Logger.log(e);
}
Logger.log(response)
if (response.getResponseCode() == 200) {
}
var result = JSON.parse(response.getContentText());
if (result.error){
continue;
return null
}
var row = []
for (var k in result.rows){
row.push([
result.rows[k].keys[0],
result.rows[k].clicks,
result.rows[k].impressions,
result.rows[k].ctr,
result.rows[k].position
]);
}
s_searchAnalytics.getRange(i,2,row.length,5).setValues(row);
}} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
}
}

TypeError: Cannot find function forEach in object in Google App Script

I keep running to Cannot find function for each in object error while trying to loop entries. Is there something I am not seeing?. Here the code. This code is supposed to fetch time data from a system via API do calculations and send email
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token'
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
}
}
response.data is probably not the array you expect. The server may be returning an error or a successful response that isn't parseable as an array. To find out, print response.data to the console and confirm it's the array you expect.
Seems my API returned an object. I figured out the way around it by using Object.keys method and it worked. Here is the working code.
function getTime() {
var range = [53, 926, 8098];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + '449625' + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
Object.keys(time_entries).forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
Object.keys(submitted_time_entries).forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
Logger.log(time_entry)
//send mail
}
});
}
}

How to perform call signing in Java scripts with scripting apps?

I Have the following problem, any help is welcome, I am trying to get result of a function and make a call, but the process is happening as it should, when I step the result in a variable The result is this:
Result URL var parameter
{time_ref = 1554817906, Date_start = 2019-03-10, account_id = xxxxxxxxxx, async_percent_completion = 0, Async_status = Job Not Started, date_stop = 2019-04-08, id = 2299845083590625}
Passing direct the value in the URL The result is this:
Manual
{time_ref = 1554817906, Date_start = 2019-03-10, account_id = xxxxxxxxxx, time_completed = 1554817907, async_percent_completion = 100, Async_status = Job Completed, date_stop = 2019-04-08, id = 2299845083590625}
What am I doing wrong that I can't get the second call I need to finalize my lawsuit?
Documentation :
https://developers.facebook.com/docs/marketing-api/insights/best-practices/?hc_location=ufi#asynchronous
function solicitacaoAssicrona(){
var service = getService()
var metricas = [
'impressions',
'reach',
'unique_clicks',
'account_currency',
'account_id',
'account_name',
'ad_id',
'ad_name',
'adset_id',
'adset_name',
'buying_type',
'campaign_id',
'campaign_name',
]
var parameters = metricas.join(',');
var url = 'https://graph.facebook.com/v3.2/act_xxxxxxxxxx/insights?fields=' + parameters + '&level=ad';
//Logger.log(url);
var report_run_id = UrlFetchApp.fetch(url, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(report_run_id.getContentText());
return result;
}
result= [19-04-09 12:28:34:334 BRT] {report_run_id=1283453988472584}
function reportId(){
var service = getService();
var report_run_id = new solicitacaoAssicrona();
//Logger.log(report_run_id);
var report = report_run_id['report_run_id'];
//var report_run_idParameters = report.toString();
var reportUrl = 'https://graph.facebook.com/v3.2/' + report;
//Logger.log(reportUrl);
var response = UrlFetchApp.fetch(reportUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
return result;
}
[19-04-09 12:30:38:457 BRT] {time_ref=1554823837, date_start=2019-03-10, account_id=xxxxxxxxx, async_percent_completion=0, async_status=Job Not Started, date_stop=2019-04-08, id=806453509753109}
function reportId(){
var service = getService();
var report_run_id = new solicitacaoAssicrona();
//Logger.log(report_run_id);
var report = report_run_id['report_run_id'];
//var report_run_idParameters = report.toString();
var reportUrl = 'https://graph.facebook.com/v3.2/806453509753109';
//Logger.log(reportUrl);
var response = UrlFetchApp.fetch(reportUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(result)
return result;
}
[19-04-09 12:31:26:785 BRT] {time_ref=1554823837, date_start=2019-03-10, account_id=xxxxxxxx, time_completed=1554823839, async_percent_completion=100, async_status=Job Completed, date_stop=2019-04-08, id=xxxxxxx}
Solved with caching, I stored the report ID in cache there worked well! Follow Documentation! https://developers.google.com/apps-script/reference/cache/cache

Undefined Error when parsing JSON in google apps script

I'm trying to parse JSON I recieved from an API call, but I keep running into the error "TypeError: Cannot read property "id" from undefined. (line 42, file "")" I'm relatively new to Apps Script. Any ideas on what's going on? I can get the payload back in JSON, but can't seem to parse it.
function getInfo() {
var url = "https://subdomain.chargify.com/subscriptions.json";
var username = "xxx"
var password = "x"
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
};
var options = {
"method": "GET",
"contentType": "application/json",
"headers": headers
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
Logger.log(data);
var id = data.subscription; // kicks back an error
// var id = data; works and returns the whole JSON payload
var ss = SpreadsheetApp.getActiveSheet()
var targetCell = ss.setActiveSelection("A1");
targetCell.setValue(id);
}
According to the documentation here
https://docs.chargify.com/api-subscriptions#api-usage-json-subscriptions-list
it returns an array of subscriptions when you call the /subscriptions.json endpoint. So probably your data object should be handled like:
for (var i=0;i<data.length;i++) {
var item = data[i]; //subscription object, where item.subscription probably works
Logger.log(JSON.stringify(item));
}
function getInfo() {
var url = "https://subdomain.chargify.com/subscriptions.json";
var username = "xxx"
var password = "x"
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
};
var options = {
"method": "GET",
"contentType": "application/json",
"headers": headers
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
for (var i = 0; i < data.length; i++) {
var item = data[i]; //subscription object, where item.subscription probably works
Logger.log(JSON.stringify(item));
var subscriptionid = item.subscription.id;
}
var ss = SpreadsheetApp.getActiveSheet()
var targetCell = ss.setActiveSelection("A2");
targetCell.setValue(subscriptionid);
}

Sending and receiving data using Jquery

I am at basic level of application development.
I wanted to know how I can send and get this data with JQuery any new version.
I also want it to support all browsers.
I'm just using simple Ajax but I know it is possible with Jquery and im not able to figure it out.
function SendData() {
var data = "action=check&uid=" + uid + "&fbuid=" + fb_uid + ";
var url = "http://www.example.com/call.php";
var ajax = new AJAXInteraction(url, CheckRate);
ajax.doPost(data);
};
function CheckRate(Content) {
response = JSON.parse(Content);
Rate = response.stat.rate;
document['getElementById']('ERate')['value'] = Rate;
};
function AJAXInteraction(url, callback) {
var req = init();
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
if (callback) callback(req.responseText);
}
}
}
this.doGet = function () {
req.open("GET", url, true);
req.send(null);
}
this.doPost = function (str) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
req.send(str);
}
};
I am able to solve first part And still dont know rest:
function SendData(){
dataString = "action=check&uid=" + uid + "&fbuid=" + fb_uid + ";
url = "http://www.example.com/call.php";
jQuery.ajax({
type: "POST",
url: url,
data: dataString,
});
};
My problem is how i will read response
function CheckRate(Content) {
response = JSON.parse(Content);
Rate = response.stat.rate;
document['getElementById']('ERate')['value'] = Rate;
};
function SendData() {
dataString = "action=check&uid=" + uid + "&fbuid=" + fb_uid + ";
url = "http://www.example.com/call.php";
jQuery.ajax({
type: "POST",
url: url,
data: dataString, // sending data
success: function (data) {
CheckRate(data); // receiving data
}
});
};
// function body should looks like this
function CheckRate(Content) {
response = JSON.parse(Content);
Rate = response.stat.rate;
document['getElementById']('ERate')['value'] = Rate;
};

Categories

Resources