Skip to content

Commit

Permalink
handling bad responses from upstream image server
Browse files Browse the repository at this point in the history
  • Loading branch information
enapupe committed Nov 2, 2023
1 parent 36c4dd7 commit a47267e
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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));
}
});

Expand Down

0 comments on commit a47267e

Please sign in to comment.