Pagination on a Shopify GET order API call - javascript

I'm trying to write a script that fetches Shopify orders and saves them into a Google Sheet.
When paginating through the Shopify order API my script only seems to pull the first 250 orders and isn't displaying any further data.
Any ideas on why it's failing to pull further orders? On logging the data, it seems to not be pulling the next URL correctly.
// Import the required modules
const sheet = SpreadsheetApp.getActive().getSheetByName("OrdersTEST");
let newSheet;
// Define the API endpoint and headers
const endpoint = "https://STOREID.myshopify.com/admin/api/2021-10/orders.json?status=any&limit=250&fields=order_number,id,email,created_at,total_price,current_total_price,financial_status,line_items,tax_lines,gateway, shipping_address,shipping_lines,note_attributes&order=created_at asc";
const apiKeyHeader = {"X-Shopify-Access-Token": "ACCESS TOCKEN"};
// Define the delay time to avoid hitting rate limit
const delayTime = 1000;
function getOrders() {
// Initial call to API to get first page of orders
var response = UrlFetchApp.fetch(endpoint, {headers: apiKeyHeader});
var data = JSON.parse(response.getContentText());
// Check if the sheet exists, if not create it
if (!sheet) {
newSheet = SpreadsheetApp.getActive().insertSheet("OrdersTEST");
}else{
newSheet = sheet;
}
// Clear the sheet
sheet.clear();
// Add column titles
newSheet.appendRow(["Order ID", "Email", "Created At", "Total Price"]);
// Write the orders data to the sheet
var orders = data.orders;
var values = [];
for (var i = 0; i < orders.length; i++) {
values.push([orders[i].id, orders[i].email, orders[i].created_at, orders[i].total_price]);
}
newSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
// Get next page URL
var link_header = response.getHeaders()["link"];
Logger.log("link_header: " + link_header);
// Loop through all pages of orders
while (link_header) {
// Wait for delay time to avoid hitting rate limit
Utilities.sleep(delayTime);
// Call API with next page URL
var next_link = link_header.match(/<(.*)>; rel="next"/)[1];
Logger.log("next_link: " + next_link);
response = UrlFetchApp.fetch(next_link, {headers: apiKeyHeader});
data = JSON.parse(response.getContentText());
link_header = response.getHeaders()["link"];
Logger.log("link_header after call: " + link_header);
// Write the orders data to the sheet
orders = data.orders;
values = [];
for (var i = 0; i < orders.length; i++) {
values.push([orders[i].id, orders[i].email, orders[i].created_at, orders[i].total_price]);
}
newSheet.getRange(newSheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
}
Logger.log("Orders data written to sheet successfully!");
}

You shouldn't use REST API Endpoint for that. Check GraphQL Reference and particularly look into Paginating results with GraphQL. Note it's not going to be one call and you have to keep in mind that there is a bucket with a limit, where each API call has its cost.

Related

How to run certain scripts under the authority of a specific user?

I was able to allow other users to add a new SKU to a sheet without unprotecting it (Original post). Now I am trying to do the inverse, to allow users to delete an SKU without unprotecting the sheet.
I started with the following, which works as expected:
function deleteEachRow(){
const ss = SpreadsheetApp.getActive();
var SHEET = ss.getSheetByName("Ordering");
var RANGE = SHEET.getDataRange();
const ui = SpreadsheetApp.getUi();
const response = ui.prompt('WARNING: \r\n \r\n Ensure the following sheets DO NOT contain data before proceeding: \r\n \r\n Accessory INV \r\n Apparel INV \r\n Pending TOs \r\n \r\n Enter New SKU:', ui.ButtonSet.OK_CANCEL);
if (response.getSelectedButton() === ui.Button.OK) {
const text = response.getResponseText();
var rangeVals = RANGE.getValues();
//Reverse the 'for' loop.
for(var i = rangeVals.length-1; i >= 0; i--){
if(rangeVals[i][0] === text){
SHEET.deleteRow(i+1);
};
};
};
};
I tried to Frankenstein the above code into the answer I was provided. Now the script runs without error but fails to delete the entered SKU as expected. This is the script I am running:
function deleteEachRow1(){
const ss = SpreadsheetApp.getActive();
var SHEET = ss.getSheetByName("Ordering");
var RANGE = SHEET.getDataRange();
const ui = SpreadsheetApp.getUi();
const response = ui.prompt('WARNING: \r\n \r\n Ensure the following sheets DO NOT contain data before proceeding: \r\n \r\n Accessory INV \r\n Apparel INV \r\n Pending TOs \r\n \r\n Delete Which SKU?:', ui.ButtonSet.OK_CANCEL);
if (response.getSelectedButton() === ui.Button.OK) {
const text = response.getResponseText();
const webAppsUrl = "WEB APP URL"; // Pleas set your Web Apps URL.
const url = webAppsUrl + "?text=" + text;
const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
// ui.alert(res.getContentText()); // You can see the response value using this line.
}
}
function doGet(e) {
const text = e.parameter.text;
const sheet = SpreadsheetApp.getActive().getSheetByName('Ordering');
var rangeVals = RANGE.getValues();
//Reverse the 'for' loop.
for(var i = rangeVals.length-1; i >= 0; i--){
if(rangeVals[i][0] === text){
SHEET.deleteRow(i+1);
};
};
myFunction();
return ContentService.createTextOutput(text);
}
// This script is from https://tanaikech.github.io/2017/07/31/converting-a1notation-to-gridrange-for-google-sheets-api/
function a1notation2gridrange1(a1notation) {
var data = a1notation.match(/(^.+)!(.+):(.+$)/);
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(data[1]);
var range = ss.getRange(data[2] + ":" + data[3]);
var gridRange = {
sheetId: ss.getSheetId(),
startRowIndex: range.getRow() - 1,
endRowIndex: range.getRow() - 1 + range.getNumRows(),
startColumnIndex: range.getColumn() - 1,
endColumnIndex: range.getColumn() - 1 + range.getNumColumns(),
};
if (!data[2].match(/[0-9]/)) delete gridRange.startRowIndex;
if (!data[3].match(/[0-9]/)) delete gridRange.endRowIndex;
return gridRange;
}
// Please run this function.
function myFunction() {
const email = "MY EMAIL"; // <--- Please set your email address.
// Please set your sheet names and unprotected ranges you want to use.
const obj = [
{ sheetName: "Ordering", unprotectedRanges: ["O5:P", "C2:E2"] },
{ sheetName: "Accessory INV", unprotectedRanges: ["E5:H"] },
{ sheetName: "Apparel INV", unprotectedRanges: ["E5:F"] },
{sheetName: "Pending TOs", unprotectedRanges: ["E6:H"] },
{sheetName: "INV REF", unprotectedRanges: ["C6:C"] },
];
// 1. Retrieve sheet IDs and protected range IDs.
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const sheets = Sheets.Spreadsheets.get(spreadsheetId, { ranges: obj.map(({ sheetName }) => sheetName), fields: "sheets(protectedRanges(protectedRangeId),properties(sheetId))" }).sheets;
const { protectedRangeIds, sheetIds } = sheets.reduce((o, { protectedRanges, properties: { sheetId } }) => {
if (protectedRanges && protectedRanges.length > 0) o.protectedRangeIds.push(protectedRanges.map(({ protectedRangeId }) => protectedRangeId));
o.sheetIds.push(sheetId);
return o;
}, { protectedRangeIds: [], sheetIds: [] });
// 2. Convert A1Notation to Gridrange.
const gridranges = obj.map(({ sheetName, unprotectedRanges }, i) => unprotectedRanges.map(f => a1notation2gridrange1(`${sheetName}!${f}`)));
// 3. Create request body.
const deleteProptectedRanges = protectedRangeIds.flatMap(e => e.map(id => ({ deleteProtectedRange: { protectedRangeId: id } })));
const protects = sheetIds.map((sheetId, i) => ({ addProtectedRange: { protectedRange: { editors: {users: [email]}, range: { sheetId }, unprotectedRanges: gridranges[i] } } }));
// 4. Request to Sheets API with the created request body.
Sheets.Spreadsheets.batchUpdate({ requests: [...deleteProptectedRanges, ...protects] }, spreadsheetId);
}
Probably the easiest way to do this would be to avoid using a button and using a checkbox with a installable edit trigger, which also has a great side effect of mobile support.
Proposed solution:
Using a checkbox
Hook it to a installable edit trigger, which runs as the user who installed the trigger. Therefore, if the owner installs the trigger, no matter who edits the sheet, the trigger runs as the owner, giving access to privileged resources including protected ranges.
The installable version runs with the authorization of the user who created the trigger, even if another user with edit access opens the spreadsheet.
Notes:
Advantage:
Code simplicity and maintainabilty. No need for webapp or any complicated setup.
Disadvantage: Security (with possible workaround)
If the code is bound to the sheet, editors of the sheet get direct access to the script of the sheet. So, any editor with malicious intentions would be able to modify the code. If the function with installable trigger has gmail permissions, any editor would be able to log all the emails of the owner. So,special attention needs to be paid to permissions requested. Note that, this is already the case with your web app setup. Any editor maybe able to modify doGet to access protected data. If the webapp is in a separate standalone script, this isn't a issue. You may also be able to fix this issue by setting the trigger at a predetermined version instead of Head version. See this answer for more information.

How to batch row data and send a single JSON payload?

I currently use a Google Apps Script on a Google Sheet, that sends individual row data to AWS API Gateway to generate a screenshot. At the moment, multiple single JSON payload requests are causing some Lambda function failures. So I want to batch the row data and then send as a single payload, so a single AWS Lambda function can then perform and complete multiple screenshots.
How can I batch the JSON payload after iterating the data on each line in the code below?
function S3payload () {
var PAYLOAD_SENT = "S3 SCREENSHOT DATA SENT";
var sheet = SpreadsheetApp.getActiveSheet(); // Use data from the active sheet
// Add temporary column header for Payload Status new column entries
sheet.getRange('E1').activate();
sheet.getCurrentCell().setValue('payload status');
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() - 1; // Number of rows to process
var lastColumn = sheet.getLastColumn(); // Last column
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn) // Fetch the data range of the active sheet
var data = dataRange.getValues(); // Fetch values for each row in the range
// Work through each row in the spreadsheet
for (var i = 0; i < data.length; ++i) {
var row = data[i];
// Assign each row a variable
var index = row[0]; // Col A: Index Sequence Number
var img = row[1]; // Col B: Image Row
var url = row[2]; // Col C: URL Row
var payloadStatus = row[lastColumn - 1]; // Col E: Payload Status (has the payload been sent)
var siteOwner = "email#example.com";
// Prevent from sending payload duplicates
if (payloadStatus !== PAYLOAD_SENT) {
/* Forward the Contact Form submission to the owner of the site
var emailAddress = siteOwner;
var subject = "New contact form submission: " + name;
var message = message;*/
//Send payload body to AWS API GATEWAY
//var sheetid = SpreadsheetApp.getActiveSpreadsheet().getId(); // get the actual id
//var companyname = SpreadsheetApp.getActiveSpreadsheet().getName(); // get the name of the sheet (companyname)
var payload = {
"img": img,
"url": url
};
var url = 'https://requestbin.herokuapp.com/vbxpsavc';
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url,options);
sheet.getRange(startRow + i, lastColumn).setValue(PAYLOAD_SENT); // Update the last column with "PAYLOAD_SENT"
SpreadsheetApp.flush(); // Make sure the last cell is updated right away
// Remove temporary column header for Payload Status
sheet.getRange('E1').activate();
sheet.getCurrentCell().clear({contentsOnly: true, skipFilteredRows: true});
}
}
}
Example individual JSON payload
{"img":"https://s3screenshotbucket.s3.amazonaws.com/realitymine.com.png","url":"https://realitymine.com"}
Example desired output result
[
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/gavurin.com.png","url":"https://gavurin.com"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/google.com.png","url":"https://google.com"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/amazon.com","url":"https://www.amazon.com"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/stackoverflow.com","url":"https://stackoverflow.com"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/duckduckgo.com","url":"https://duckduckgo.com"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/docs.aws.amazon.com","url":"https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-features.html"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/github.com","url":"https://github.com"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/github.com/shelfio/chrome-aws-lambda-layer","url":"https://github.com/shelfio/chrome-aws-lambda-layer"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/gwww.youtube.com","url":"https://www.youtube.com"},
{"img":"https://s3screenshotbucket-useast1v5.s3.amazonaws.com/w3docs.com","url":"https://www.w3docs.com"}
]
Modifications
Do not call UrlFetchApp methods in a loop unless no other way. Although Google offers generous quota, it is not unlimited, and you will quickly burn through it on any substantial amount of rows and send frequency.
Use modern ES6 features like map to convert rows of values into objects in the format of the desired payload. Note that you will have to enable V8 runtime to use them.
What follows is a runnable test snippet showcasing how you could have modified your script. I opted to exclude status update logic from it, as it is up to you to decide how to update the status in case of batch update failure:
//TEST MOCKS:
const SpreadsheetApp = {
getActiveSheet() {
const Sheet = {
getLastRow() { return 3; },
getLastColumn() { return 5; },
getDataRange() {
const Range = {
getValues() {
return new Array(Sheet.getLastRow())
.fill([])
.map(
(r,ri) => new Array(Sheet.getLastColumn())
.fill(`mock row ${ri}`)
.map((c,ci) => `${c} cell ${ci}`)
);
}
};
return Range;
}
};
return Sheet;
}
};
const UrlFetchApp = {
fetch(uri, options) {
console.log({ uri, options });
}
};
//END MOCKS;
const sendToS3 = () => {
var PAYLOAD_SENT = "S3 SCREENSHOT DATA SENT";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var lastColumn = sheet.getLastColumn();
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var siteOwner = "email#example.com";
const appURI = 'https://hfcrequestbin.herokuapp.com/vbxpsavb';
const payloads = data.map(([index, img, url]) => ({ img, url }));
const options = {
'method': 'post',
'payload': JSON.stringify(payloads)
};
const response = UrlFetchApp.fetch(appURI, options);
}
sendToS3();
Notes
When batching POST payloads, keep in mind that there is a quota on
maximum body size per request (currently 50 MB).
Do not call I/O (input/output) methods such as getRange, getValue in a loop, they are slow by nature, use batch methods like getDataRange, getValues, setValues, etc and perform all modifications on in-memory arrays only.
Use activate methods only when you explicitly want to change the focus, do not rely on it to determine a range. Just use normal references to cells obtained through methods like getRange.
Try sending the data as a list/Array. And on the server side iterate over the list/Array.
eg:
{
"payload": [{
"img": "https://s3screenshotbucket.s3.amazonaws.com/website1.com.png",
"url": "https://website1.com"
}, {
"img": "https://s3screenshotbucket.s3.amazonaws.com/website2.com.png",
"url": "https://website2.com"
}]
}

How do I wait until entire array is pushed to execute a function?

I am creating a payout API for my site, this one is set up around Monero and I am fetching the values needed to make payments and where to send them from my MongoDB database. I am using Mongoose to do this
I have everything mapped out, it grabs from an array the total net value for that day that needs to be paid out and it grabs from another array the latest wallet entry so it knows where to send the amount to.
The problem arises when I'm trying to structure a new array with this data, pushing this data into it.
Monero intrinsically only allows one transaction to be sent out at a time, locking your leftover balance and the amount sent out until that one transaction has been fully confirmed. The one transaction can be split into multiple transactions but it all has to be sent as "one" big chunk.
So when I send the request to Monero it has to include an array of every wallet and what amount each wallet is receiving.
When I'm pushing to the array I noticed it executes the Transfer Monero function for every time it pushes to the array. How do I make it so the array is pushed completely first with every possible value that meets my if statement (Date is today, paymentStatus is set to false, the amount due is not equal or below 0) before sending that variable over for the Transfer Monero function to use?
I've already tried using return functions, etc. Not sure how to implement async/await or Promises
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var moment = require('moment');
var User = require('../models/user');
var moneroWallet = require('monero-nodejs');
var Wallet = new moneroWallet('127.0.0.1', 18083);
var destinations = []
var xmrnet = []
// connect to MongoDB
mongoose.connect('mongodb://)
// Fetch IDs
function getID(){
var cursor = User.find({}, function (err, users) {
}).cursor();
return cursor;
}
var cursor = getID();
cursor.on('data', function(name){
var id = name.id
// Map all users using IDs
function getUsers(){
var cursor = User.findById(id, function (err, users) {
}).cursor();
return cursor;
}
var cursor = getUsers();
cursor.on('data', function(user){
net = user.netHistory.map(element => element)
order = user.orderHistory.map(element => element)
userWallets = user.userWallets.map(element => element)
var today = moment();
// date is today? validation
for (var i = 0; i < net.length; i++){
netDate = net[i].net_date_time
netStatus = net[i].paymentStatus
netUSD = net[i].current_usd_net
xmrnet = net[i].xmr_net
for (var j = 0; j < userWallets.length; j++){
xmrwalletsU = userWallets[j].xmr_wallet
if(xmrwalletsU !== ''){
xmrwallet = xmrwalletsU
}
}
var Dateistoday = moment(netDate).isSame(today, 'day');;
if (Dateistoday === true && xmrnet !== 0 && netStatus === false){
console.log('its true')
netid = net[i].id
var destinationsU = [{amount: xmrnet, address: xmrwallet}]
destinations.push(destinationsU)
console.log(destinations)
// problem is right here with destinations^ it pushes one by one
// problem over here as well as wallet.transfer executes one by one by the time it gets to the second, the balance is already locked, unable to send
Wallet.transfer(destinations).then(function(transfer) {
console.log(transfer);
var payouts = {
payout_date_time: Date(),
payout_usd_amount: netUSD,
xmr_wallet: xmrwallet,
xmr_txid: transfer.tx_hash,
}
// add payout to payoutHistory array
User.findByIdAndUpdate(id, {"$addToSet": { 'payoutHistory': [payouts]}},
function(err, user) {
if(err) { console.log(err) }
else {
console.log()
};
})
// update paymentStatus of specific net entry to true
User.updateMany({
"_id": id,
"netHistory._id": netid
}, {
"$set": {
"netHistory.$.paymentStatus": true
}
}, function(error, success) {
})
})
}
}
})
})

Closures, loops, and promises

I've read several posts on the subject, but unfortunately struggling with my situation.
I am pulling some urls from an array of urls and then using those links to obtain (let's say) the title of the page from those subsites. At the end I want a list of original urls and an array of titles (from the sublinks). i.e., go into a site/domain, find some links, curl those links to find page titles.
Problem is that my titleArray just returns a Promise and not the actual data. I'm totally not getting closures right and promises. Code runs in node as is. I'm using personal sites in my real code, but substituted common sites to show an example.
const popsicle = require('popsicle');
var sites = ['http://www.google.com','http://www.cnn.com'];
// loop through my sites (here I'm just using google and cnn as a test
for(var i=0;i<sites.length;i++) {
// call function to pull subsites and get titles from them
var titleArray = processSites(sites[i]);
console.log(sites[i] + ": " + titleArray);
}
// get request on site and then get subsites
function processSites(url) {
return popsicle.get(url)
.then(function(res) {
var data = res.body;
// let's assume I get another collection of URLs
// that I pull from the main site
var subUrls = ['http://www.yahoo.com','http://www.espn.com'];
var titleArray = [];
for(var j=0;j<subUrls.length;i=j++) {
var title = processSubSites(subUrls[j])
titleArray.push(title);
}
return titleArray;
});
}
function processSubSites(url) {
return popsicle.get(url)
.then(function(res) {
var data = res.body;
// let's say I pull the title of the site somehow
var title = "The Title for " + url;
console.log(title);
return title;
});
}
The result after running this is:
http://www.google.com: [object Promise]
http://www.cnn.com: [object Promise]
The Title for http://www.espn.com
The Title for http://www.espn.com
The Title for http://www.yahoo.com
The Title for http://www.yahoo.com
whereas it should be:
http://www.google.com: ['The Title for http://www.yahoo.com', 'The Title for http://www.espn.com']
http://www.cnn.com: ['The Title for http://www.yahoo.com', 'The Title for http://www.espn.com']
...
You cannot return normal data from inside a Promise. You need to return another Promise to make it chainable. To process multiple Promise objects in loop, you need to push them in an array and call Promise.all(array);
const popsicle = require('popsicle');
var sites = ['http://www.google.com','http://www.cnn.com'];
var titleArrayPromises = [];
// loop through my sites (here I'm just using google and cnn as a test
for(var i=0;i<sites.length;i++) {
titleArrayPromises.push(processSites(sites[i]));
}
var titleArray = [];
Promise.all(titleArrayPromises).then(function (titleArrays) {
for(var i=0; i<titleArrays.length; i++) {
titleArray.concat(titleArrays[i])
}
// You now have all the titles from your site list in the titleArray
})
function processSites(url) {
return popsicle.get(url)
.then(function(res) {
var data = res.body;
// let's assume I get another collection of URLs
// that I pull from the main site
var subUrls = ['http://www.yahoo.com','http://www.espn.com'];
var titlePromiseArray = [];
for(var j=0;j<subUrls.length;j++) {
titlePromiseArray.push(processSubSites(subUrls[j]));
}
return Promise.all(titlePromiseArray);
});
}
function processSubSites(url) {
return popsicle.get(url)
.then(function(res) {
var data = res.body;
// let's say I pull the title of the site somehow
var title = "The Title for " + url;
return Promise.resolve(title);
});
}

Are there promises on Google Apps Script?

I have a form that my users enter data and I use onFormSubmit to trigger a script that creates a CSV based on the data inserted and after I create the CSV file I delete the data. Problem is that I am deleting the data before creating CSV file. Usually I would just make a promise call but I think it is not possible with Google Apps Script. Is there any alternative to it?
So my complete code is here:
More insight about what it does:
When I receive a new form entry, the "Avaliacao" sheet gets updated and will trigger testTrigger().
Then, it will write the email and the usercity in the LastUser city so it can lookup for some data that I will use to build my CSV file. But the saveAsCsv function is called before the sheet completed its VLOOKUP calls. So my CSV file is empty.
Another issue that I have with synchronization is that if I enable the sLastUser.clear(); line it will also delete before creating the CSV.
function testTrigger () {
//open the sheets
var SS = SpreadsheetApp.getActiveSpreadsheet();
var sAvaliacao = SS.getSheetByName("Avaliação");
var sPreCSV = SS.getSheetByName("PreCSV");
var sInput = SS.getSheetByName("Input");
var sLastUser = SS.getSheetByName("LastUser");
var dAvaliacao = sAvaliacao.getDataRange().getValues();
var dInput = sInput.getDataRange().getValues();
var avaliacaoLastRow = sAvaliacao.getLastRow()-1;
var userEmail = dAvaliacao[avaliacaoLastRow][2];
var userCity = dAvaliacao[avaliacaoLastRow][5];
var userId = dInput[3][52];
sLastUser.appendRow([userEmail, userCity]);
saveAsCSV(userId);
// sLastUser.clear(); <== this is the line where I can`t enable
}
function saveAsCSV(csvName) {
// Name
var fileName = String(csvName) + ".csv"
// Calls convertcsv
var csvFile = convertOutputToCsv_(fileName);
// create the file on my drive
DriveApp.createFile(fileName, csvFile);
}
function convertOutputToCsv_(csvFileName) {
// open sheets
var sPreCSV = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PreCSV");
var cont = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Input").getDataRange().getValues()[3][50] + 1;
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PreCSV").getRange(1, 1, cont, 3);
try {
var data = ws.getValues();
var csvFile = undefined;
// Loop through the data in the range and build a string with the CSV data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// Join each row's columns
// Add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
Now with engine v8 Promise is defined object
Indeed, the JS engine used by Google Apps Script does not support promises (Logger.log(Promise); shows it's undefined).
To make sure that spreadsheet changes take effect before proceeding further, you can use SpreadsheetApp.flush().
Another relevant feature is event object passed by the trigger on Form Submit: it delivers the submitted data to the script without it having to fish it out of the spreadsheet.
There are no native Promises in GAS. With that said you can write your code in ES6/ESnext and make use of promises that way. To see how you can configure modules to expose the to the global scope see my comment here.
By doing this you can take advantage of promises. With that said depending on the size of your project this may be overkill. In such a case I'd advise using simple callbacks if possible.

Categories