Help

Re: ReferenceError: btoa is not defined

373 0
cancel
Showing results for 
Search instead for 
Did you mean: 
Rasmus
5 - Automation Enthusiast
5 - Automation Enthusiast

Hi all,

I've found a script that I've used as a script app to compress all of the images in my tables. Now I would like to turn that into an automation, so when I upload a new image it will use my tinypng account's api to compress the image. I've changed the script a bit in order for it to work as an automation but I don't know how to fix this error. 

My code:

 

// Modify these to your own values.
let tinyPngApiKey = '00000';
let airtableAttachmentSource = 'Billeder';
let airtableAttachmentDestination = 'Billeder';
let airtableColumnToLog = 'Billeder';

// Don't change these unless you know what you're doing.
let table = base.getTable("Anlæg");
let view = table.getView("Alle anlæg");
let queryResult = await view.selectRecordsAsync();

for (let record of queryResult.records) {
  let 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()) {
      let recordAttachmentUrl = attachment['url'];

      console.log(`Compressing ${record.getCellValue(airtableColumnToLog)} (Image ${i + 1})`);

      let request = await fetch('https://api.tinify.com/shrink', {
        body: JSON.stringify({'source': {'url': recordAttachmentUrl}}),
        headers: {
          Authorization: 'Basic ' + btoa('api:' + tinyPngApiKey),
          'Content-Type': 'application/json'
        },
        method: 'POST'
      })

      const json = await request.json();

      // Checks that the API didn't fail.
      if (request.status == 201) {
        let percentReduced = Math.round((1 - json.output.ratio) * 100);
        let kbReduced = (json.input.size - json.output.size) / 1024;

        console.log('Panda just saved you ' + percentReduced + '% (' + Math.round(kbReduced) + 'KB).');

        // Add the compressed image URL to the array.
        compressedImageUrls.push({ url: json['output']['url'] });
      }
    }

    // Update the record with all the compressed image URLs.
    await table.updateRecordAsync(record.id, {
      [airtableAttachmentDestination]: compressedImageUrls,
    });
  }
}

 

 Any help would be much appreciated. 

Thanks

1 Reply 1