I have a script that retrieves data from a google photos library using google apps script and writes the data to a airtable base, I have no coding experience and have generated the script through Chat-gpt. The script retrieves all the album names and the number of photos in each albums.
What I want to achieve is that a script should delete all the existing records in the specified base before writing new records to it, using google apps script. Can someone please help me by modifying the script for me?
Here is the script that i use to retrieve data from google photos library and write the data to an airtable base:
function syncAlbumData() {
var apiKey = "apiKey-accessToken"; //paste your api or access token here
var baseId = "Base-ID"; //paste your base id here
var tableName = "tab3"; //paste your table name here
// Get albums from Google Photos
var albums = [];
var nextPageToken = null;
do {
var pageData = getGooglePhotosAlbums(nextPageToken);
if (pageData.albums && Array.isArray(pageData.albums)) {
albums = albums.concat(pageData.albums);
}
nextPageToken = pageData.nextPageToken;
} while (nextPageToken);
// Prepare records for Airtable
var records = [];
albums.forEach(function(album) {
var record = {
"fields": {
"Album Name": album.title,
"Number of Photos": album.mediaItemsCount
}
};
records.push(record);
});
// Write records to Airtable
writeRecordsToAirtable(records, apiKey, baseId, tableName);
}
function getGooglePhotosAlbums(pageToken) {
var options = {
method: "GET",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
};
var url = "https://photoslibrary.googleapis.com/v1/albums";
if (pageToken) {
url += "?pageToken=" + pageToken;
}
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
return data;
}
function writeRecordsToAirtable(records, apiKey, baseId, tableName) {
var url = "https://api.airtable.com/v0/" + baseId + "/" + tableName;
var headers = {
"Authorization": "Bearer " + apiKey,
"Content-Type": "application/json"
};
// Batch the records into groups of 10
var batchSize = 10;
var batchedRecords = [];
while (records.length > 0) {
batchedRecords.push(records.splice(0, batchSize));
}
// Send requests for each batch
batchedRecords.forEach(function(batch) {
var payload = {
"records": batch
};
var options = {
"method": "POST",
"headers": headers,
"payload": JSON.stringify(payload)
};
UrlFetchApp.fetch(url, options);
});
}