Optimize 'Keep First Row' Feature to Reduce API Requests

Refactored the code to improve the efficiency of the "Keep First Row" feature in the Google Sheets interaction.
Updated the code to fetch and update the first row data outside the loop, reducing the number of unnecessary API requests.
This optimization ensures that the first row is updated only once, resulting in improved performance and avoiding quota exceeded errors.
Resolves the issue of excessive API requests when using the "Keep First Row" option.
Tested and verified the fix to ensure correct behavior in n8n workflows.
This commit is contained in:
Panchin99 2023-09-18 17:44:39 +05:30 committed by कारतोफ्फेलस्क्रिप्ट™
parent f98c4b8ac0
commit f9b92b84d9
No known key found for this signature in database
GPG key ID: 9300FF7CDEA1FBAA

View file

@ -163,6 +163,10 @@ export async function execute(
): Promise<INodeExecutionData[]> {
const items = this.getInputData();
// Initialize variables to store the first row data and flag to check if it has been updated
let firstRowData: string[][] | undefined;
let firstRowUpdated = false;
for (let i = 0; i < items.length; i++) {
const clearType = this.getNodeParameter('clear', i) as string;
const keepFirstRow = this.getNodeParameter('keepFirstRow', i, false) as boolean;
@ -196,13 +200,18 @@ export async function execute(
range = sheetName;
}
if (keepFirstRow) {
const firstRow = await sheet.getData(`${range}!1:1`, 'FORMATTED_VALUE');
await sheet.clearData(range);
await sheet.updateRows(range, firstRow as string[][], 'RAW', 1);
} else {
await sheet.clearData(range);
if (!firstRowUpdated && keepFirstRow) {
// Fetch the first row data only once
firstRowData = await sheet.getData(`${range}!1:1`, 'FORMATTED_VALUE');
firstRowUpdated = true;
}
await sheet.clearData(range);
}
if (firstRowData && firstRowUpdated) {
// Update the first row data outside the loop
await sheet.updateRows(sheetName, firstRowData, 'RAW', 1);
}
return items;