Post array value after switch using for loop - javascript

I have a script that iterates through an array and does a POST call to my API to create new records.
When it runs I see new records are created for each value in the array but I am unable to pass through the tens/u_department value (the array value) I'm having to do a switch because the input value is not valid in that format in my API.
How can I get the following responses from the below requests.
Requests
{"caller_id":"caller","description":"description","u_department":"A B.C"}
{"caller_id":"caller","description":"description","u_department":"D E.F"}
{"caller_id":"caller","description":"description","u_department":"H I.J"}
Desired Responses
{"result":{"caller_id":"caller","description":"description","u_department":"A B.C"},"record":"1"}}
{"result":{"caller_id":"caller","description":"description","u_department":"D E.F"},"record":"2"}}
{"result":{"caller_id":"caller","description":"description","u_department":"G H.I"},"record":"3"}}
Script
//Input tenants "ABC, DEF, GHI....."
var tens = "ABC, DEF, GHI"
console.log(tens);
var realten = input.tenants;
var realten = realten.split(',');
console.log(realten);
var letters = tens.split(',').map(string=>string.trim());
console.log(letters);
//Send data
var data = {};
var caller_id = "caller";
data.caller_id = caller_id;
var description = "description";
data.description = description;
//Convert tens to proper format
var site = {};
switch (realten[0]) {
case 'ABC':
site = "A B.C";
break;
case 'DEF':
site = "D E.F";
break;
case 'GHI':
site = "G H.I";
break;
case 'JKL':
site = "J K.L";
break;
case 'MNO':
site = "M N.O";
break;
}
var u_department = site;
data.u_department = u_department;
console.log(data)
//POST options
var options = {
'endpoint': 'test',
'path':'/api/table/records',
'method': 'POST',
"headers": {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxx",
"Content-Type": "application/json"
} };
//I create following function:
function sendData(data) {
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
});
req.write(JSON.stringify(data));
}
//end try send for each array item:
for (var i=0; i<letters.length;i++) {
sendData(data[i]);
}

According to OP, sendData(data); is the correct solution.

Related

"Logging output too large. Truncating output..."

I'm trying to pull data from Airtable using Apps Scripts but all of it doesn't transfer over due to size. What do I need to add/change in order for it work?
function importCA() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ca_sheet = ss.getSheetByName("CA")
var ca = getCA();
ca_sheet.getRange(1,1, ca.length, ca[00].length).setValues(ca)
}
function getCA() {
var ca = requestAirtable();
//console.log("ca: ", ca)
var ca_info = []
ca_info.push(["Name", "Emails", "Districts", "Job Title", "Course", "Completed", "Start Dates"])
for(i=0; i<ca.length; i++) {
var fields = ca[i].fields;
ca_info.push([
fields.Name,
fields.Emails,
fields.Districts,
fields.Title,
fields.Course,
fields.Completed,
fields.StartDates,
])
}
console.log("CA ", ca_info)
return ca_info;
}
function requestAirtable() {
var url = "[removed]"
var headers ={
"Authorization": "[removed]",
"Content-type" : "application/json"
}
var options = {
headers: headers,
method: "GET"
}
var response = UrlFetchApp.fetch(url, options).getContentText();
var result = JSON.parse(response);console.log("result: ", result)
return result.records
}
I tried to altering the line:
for(i=0; i<ca.length; i++) {
but didn't work.
If you must log it to console, you could always log it while you are pushing it to the array instead of trying to log the entire array later.
console.log(ca_info.push([
fields.Name,
fields.Emails,
fields.Districts,
fields.Title,
fields.Course,
fields.Completed,
fields.StartDates
])

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

Is it possible to use Break to jump out of or skip crawling function?

Hi i would like to know if it is possible use "break" or any other method to skip the crawling function after running the script for the first time and just use the array variable that contains the crawling information for the next user request.
let glossary = [];
/** Initialise crawling and save it into glossary array */
function init() {
const glossary_url = 'https://xxxx';
const headers = {
cookie: 'cookies:kdkjslkd424'
};
const options = {
url: glossary_url,
method: 'GET',
headers: headers
};
request(options, function (error, response, body) {
const newDom = new jsdom(body);
const $ = require('jquery')(newDom.window);
$('ul > li > span[style="line-height:1.6;"]').each(function (index, element) {
let text = element.textContent.trim(); // Get text from html
let splitText = text.split(' = '); // split text by =
//console.log(text);
if (splitText.length > 1) {
glossary.push({
key: splitText[0].trim(),
value: splitText[1],
value2: splitText[2]
});
}
});
//console.log(glossary);
findMatch('DPDL');
});
}
break init;
function findMatch (key){
for(i = 0; i < glossary.length ; i++) {
if (glossary[i].key === key){
// console.log (glossary[i].value );
// console.log(glossary[i].key);
// console.log(glossary[i].value2);
// console.log(key);
console.log(key + ' = ' + glossary[i].value + ' ' + glossary[i].value2 );
}
}
}
init();
break or skip the crawl function if user wants to search another value it will just find in the glossary array glossary = [] and not crawl again as it takes long time

Node.JS and Object.Keys with json

The Code:
(URL is a working rest api that passes json data)
var request = require('request');
var username = "user";
var password = "pass";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var url = "URL";
request(
{
method: "GET",
url : url
},
function (error, response, data) {
console.log(data);
var initial_index = Object.keys(data.sites)[0];
var product_index = Object.keys(data.sites[initial_index].products)[0];
var order_id = data.purchase_id;
var title = data.sites[initial_index].products[product_index].title;
var content = data.sites[initial_index].products[product_index].description;
var image = data.sites[initial_index].products[product_index].image;
var total_price = data.sites[initial_index].prices.final_price;
var quantity = data.sites[initial_index].products[product_index].input_fields.quantity;
var sold_by = data.sites[initial_index].info.name;
var order_status = data.sites[initial_index].status;
var datatwo = {
"status": "published",
"order_id": order_id,
"title": title,
"content": content,
"image": image,
"final_price": total_price,
"quantity": quantity,
"sold_by": sold_by,
"order_status": order_status
};
}
);
I receive this error when running the code. How can it be resolved?
var initial_index = Object.keys(data.sites)[0];
^
TypeError: Cannot convert undefined or null to object
You're not parsing the JSON (which is text) you get back. Add this at the top of your request callback:
data = JSON.parse(data);
E.g.:
request(
{
method: "GET",
url : url
},
function (error, response, data) {
data = JSON.parse(data);
var initial_index = Object.keys(data.sites)[0];
// ...
One you've parsed it, you'll have an object tree you can traverse.

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

Categories

Resources