I currently have a Google Apps Script that fetches album titles and the count of photos per album. However, I need to delete all existing entries in a specific table prior to inserting new data. Below is the script I’m working with to gather data from the Google Photos library and add it to my Airtable table:
function updateAlbumInfo() {
var apiKey = ''; // enter your API key here
var baseId = ''; // enter your base ID here
var table = 'tab3'; // specify your table name here
// Fetch albums from Google Photos
var allAlbums = [];
var token = null;
do {
var currentPage = fetchAlbumsFromGooglePhotos(token);
if (currentPage.albums && Array.isArray(currentPage.albums)) {
allAlbums = allAlbums.concat(currentPage.albums);
}
token = currentPage.nextPageToken;
} while (token);
// Build records for Airtable
var dataRecords = [];
allAlbums.forEach(function(album) {
var recordEntry = {
'fields': {
'Album Title': album.title,
'Photo Count': album.mediaItemsCount
}
};
dataRecords.push(recordEntry);
});
// Remove existing records in Airtable
deleteExistingRecords(apiKey, baseId, table);
// Insert the new records
insertRecordsIntoAirtable(dataRecords, apiKey, baseId, table);
}
function fetchAlbumsFromGooglePhotos(pageToken) {
var requestOptions = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
};
var apiUrl = 'https://photoslibrary.googleapis.com/v1/albums';
if (pageToken) {
apiUrl += '?pageToken=' + pageToken;
}
var response = UrlFetchApp.fetch(apiUrl, requestOptions);
return JSON.parse(response.getContentText());
}
function deleteExistingRecords(apiKey, baseId, table) {
var url = 'https://api.airtable.com/v0/' + baseId + '/' + table;
var headers = {
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json'
};
// Implement deletion logic here
// Example: fetch all records and delete them in batches
}
function insertRecordsIntoAirtable(records, apiKey, baseId, table) {
var url = 'https://api.airtable.com/v0/' + baseId + '/' + table;
var headers = {
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json'
};
var size = 10;
var chunks = [];
while (records.length > 0) {
chunks.push(records.splice(0, size));
}
chunks.forEach(function(chunk) {
var payload = {
'records': chunk
};
var options = {
'method': 'POST',
'headers': headers,
'payload': JSON.stringify(payload)
};
UrlFetchApp.fetch(url, options);
});
}
As I am a beginner in programming and utilized a chatbot to generate this code, I’m struggling to add a step for removing all previous entries in the table before updating it. Could anyone guide me on how to incorporate that into my script?