async function getImage()

in lib/api.ts [168:240]


async function getImage(page: Page): Promise<ImageData> {
  const image: ImageData = {
    src: `/frames/${page.key}.png`,
    height: 0,
    width: 0,
  };

  console.log(image.src);

  try {
    const dimensionsFromDisk = fs.readFileSync(getImageDataPath(page.key));
    const dimensions = JSON.parse(dimensionsFromDisk.toString());
    image.height = dimensions.height;
    image.width = dimensions.width;
    console.log(`Image for [${page.key}] found locally.`);
  } catch (er) {
    console.log(`No image for [${page.key}] found locally...`);

    try {
      await retry(
        async () => {
          const response = await fetch(
            `https://api.figma.com/v1/images/${page.fileKey}?ids=${page.id}&format=png&scale=1`,
            {
              headers: {
                "X-FIGMA-TOKEN": process.env.FIGMA_AUTH_TOKEN,
              },
            }
          );
          const contentType = response.headers.get("Content-Type");
          if (contentType === "application/json; charset=utf-8") {
            const json = await response.json();
            if (json.images && json.images[page.id]) {
              const imageUrl = json.images[page.id];
              console.log(`Image generation for [${page.key}] was successful!`);
              try {
                const dimensions = await saveImageToDisk(imageUrl, page.key);
                image.height = dimensions.height;
                image.width = dimensions.width;
                console.log("Image saved to disk successfully.");
              } catch (er) {
                console.log(`There was a problem saving the image to disk.`);
                console.log(er);
              }
            } else {
              throw new Error(JSON.stringify(json));
            }
          } else {
            throw new Error(await response.text());
          }
        },
        {
          retries: RETRY_LIMIT,
          minTimeout: RETRY_TIMEOUT,
          onRetry: (er) => {
            console.log(
              `There was a problem fetching the image for [${page.key}]. Retrying...`
            );
            console.log(er);
          },
        }
      );
    } catch (er) {
      console.log(
        `There was a problem fetching the image for [${page.key}]. Giving up.`
      );
      console.log(er);
      console.log(image);
    }
  }

  return image;
}