Hey Sho, I used ChatGPT to fix the btoa error and it worked! When I first started off, it gave me errors and I just copied and pasted the errors and kept trying. I was about to give up and move on, and then I pasted the last error and it seemed as though ChatGPT was getting frustrated on its own and wrote me a very long code which just happened to work! 😅 See the code below! I just want to say thank you once again! You started me off, which really narrowed down the issues to this solution! 5-stars Sho!
// Replace 'xxx' with your actual TinyPNG API key
const tinyPngApiKey = 'xxx';
const airtableAttachmentSource = 'Image';
const airtableAttachmentDestination = 'Image Compression';
// Access the "Inventory - Factory" table and "Image Compression" view
const table = base.getTable('Inventory - Factory');
const view = table.getView('Image Compression');
// Retrieve records from the specified view
const queryResult = await view.selectRecordsAsync();
// Function to encode a string to Base64
function encodeToBase64(str) {
const base64Chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let result = '';
for (let i = 0; i < str.length; i += 3) {
const group = (str.charCodeAt(i) << 16) | (str.charCodeAt(i + 1) << 8) | str.charCodeAt(i + 2);
result +=
base64Chars.charAt((group >> 18) & 63) +
base64Chars.charAt((group >> 12) & 63) +
base64Chars.charAt((group >> 6) & 63) +
base64Chars.charAt(group & 63);
}
return result;
}
// Function to compress and save images for a record
async function compressAndSaveImages(record) {
const attachments = record.getCellValue(airtableAttachmentSource);
let compressedImageUrls = [];
if (attachments && attachments.length > 0) {
// Iterate through each attachment in the field
for (let [i, attachment] of attachments.entries()) {
const recordAttachmentUrl = attachment['url'];
console.log(`Compressing ${record.getCellValue(airtableAttachmentSource)} (Image ${i + 1})`);
const apiKey = 'api:' + tinyPngApiKey;
const encodedApiKey = encodeToBase64(apiKey);
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + encodedApiKey,
},
body: JSON.stringify({ source: { url: recordAttachmentUrl } }),
});
const json = await request.json();
// Checks that the API didn't fail
if (request.status == 201) {
const compressedImageUrl = json.output.url;
compressedImageUrls.push({ url: compressedImageUrl });
}
}
// Update the record with all the compressed image URLs
await table.updateRecordAsync(record.id, {
[airtableAttachmentDestination]: compressedImageUrls,
});
console.log(`Images compressed and saved for record: ${record.id}`);
}
}
// Process each record in the view
for (const record of queryResult.records) {
await compressAndSaveImages(record);
}