/// <reference types="@fastly/js-compute" />
import EXIF from 'exif-js';

const handler = async (event) => {
  // Get the request from the client.
  const req = event.request
  
  // Get our backend response
  const beresp = await fetch(req, { backend: "origin_0" });
  const contentType = beresp.headers.get(`Content-Type`);

  // Extract exif tags, if this is an image request
  if (contentType && contentType.startsWith(`image/`)) {
    const data = await beresp.arrayBuffer();
    const exifTags = EXIF.readFromBinaryFile(data) || {};

    // Add all tags as headers, if there are tags
    Object.entries(exifTags).forEach(([tag, value]) =>
      beresp.headers.set(`Edge-Exif-${tag}`, value)
    );
  }
  
  // Send the response on to the client.
  return beresp;
};
  
addEventListener("fetch", event => event.respondWith(handler(event)));