From a47267e4d50e5dfe27e441c2d4613165acee49a8 Mon Sep 17 00:00:00 2001 From: Iacami Gevaerd Date: Thu, 2 Nov 2023 15:59:33 -0300 Subject: [PATCH] handling bad responses from upstream image server --- app.js | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/app.js b/app.js index ac05e8b..778ee5d 100644 --- a/app.js +++ b/app.js @@ -8,13 +8,17 @@ const PORT = 8080; const HOST = "0.0.0.0"; const BASE_STORAGE_IMAGE_URL = "https://storage.googleapis.com"; -const getImage = (path) => fetch(path).then((res) => res.arrayBuffer()); +const getImage = (path) => + fetch(path).then(async (r) => ({ + data: await r.arrayBuffer(), + status: r.status, + })); const getFormat = (webp, avif) => { return avif ? "avif" : webp ? "webp" : "jpeg"; }; app.get("/healthy", (req, res) => { - res.send("yes"); + res.send("yep."); }); app.get("*", async (req, res) => { @@ -34,21 +38,25 @@ app.get("*", async (req, res) => { const height = Number(searchParams.get("h")) || undefined; const format = getFormat(webp, avif); - const i = await getImage(href); - const processedImage = await sharp(i) + const { data, status } = await getImage(href); + if (status > 399) { + return res + .status(415) + .send("upstream server did not respond with a valid status code"); + } + + const processedImage = await sharp(data) .rotate() .resize({ width, height }) .toFormat(format, { quality }); - console.log(pathname, href); - return res .set("Cache-Control", "public, max-age=15552000") .set("Vary", "Accept") .type(`image/${format}`) .send(await processedImage.toBuffer()); } catch (e) { - res.status(500).send(JSON.stringify(e)); + return res.status(500).send(JSON.stringify(e)); } });