Skip to content

Commit a47267e

Browse files
committed
handling bad responses from upstream image server
1 parent 36c4dd7 commit a47267e

1 file changed

Lines changed: 15 additions & 7 deletions

File tree

app.js

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,17 @@ const PORT = 8080;
88
const HOST = "0.0.0.0";
99
const BASE_STORAGE_IMAGE_URL = "https://storage.googleapis.com";
1010

11-
const getImage = (path) => fetch(path).then((res) => res.arrayBuffer());
11+
const getImage = (path) =>
12+
fetch(path).then(async (r) => ({
13+
data: await r.arrayBuffer(),
14+
status: r.status,
15+
}));
1216
const getFormat = (webp, avif) => {
1317
return avif ? "avif" : webp ? "webp" : "jpeg";
1418
};
1519

1620
app.get("/healthy", (req, res) => {
17-
res.send("yes");
21+
res.send("yep.");
1822
});
1923

2024
app.get("*", async (req, res) => {
@@ -34,21 +38,25 @@ app.get("*", async (req, res) => {
3438
const height = Number(searchParams.get("h")) || undefined;
3539
const format = getFormat(webp, avif);
3640

37-
const i = await getImage(href);
38-
const processedImage = await sharp(i)
41+
const { data, status } = await getImage(href);
42+
if (status > 399) {
43+
return res
44+
.status(415)
45+
.send("upstream server did not respond with a valid status code");
46+
}
47+
48+
const processedImage = await sharp(data)
3949
.rotate()
4050
.resize({ width, height })
4151
.toFormat(format, { quality });
4252

43-
console.log(pathname, href);
44-
4553
return res
4654
.set("Cache-Control", "public, max-age=15552000")
4755
.set("Vary", "Accept")
4856
.type(`image/${format}`)
4957
.send(await processedImage.toBuffer());
5058
} catch (e) {
51-
res.status(500).send(JSON.stringify(e));
59+
return res.status(500).send(JSON.stringify(e));
5260
}
5361
});
5462

0 commit comments

Comments
 (0)