Skip to content

Commit

Permalink
fix: improve imageProxy error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ndom91 committed Aug 11, 2024
1 parent 2a81b03 commit c0f15c7
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions apps/backend/src/lib/imageProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const ipx = createIPX({
storage: ipxFSStorage(),
httpStorage: ipxHttpStorage({
allowAllDomains: true,
ignoreCacheControl: true,
}),
});

Expand All @@ -28,6 +29,7 @@ export const imageProxyHandler = async (c: Context) => {
status: 200,
headers: {
"x-cache": "HIT",
"x-image-proxy": "0.0.1",
"Content-Type": cachedResponse.type,
'cache-control': 'max-age=31536000, public, s-maxage=31536000',
},
Expand All @@ -37,12 +39,23 @@ export const imageProxyHandler = async (c: Context) => {
const response = await createIPXWebServer(ipx)(new Request(targetUrl))

const clonedResponse = response.clone()
const data = await clonedResponse.blob()
let data = await clonedResponse.blob()

if (!response.ok) {
// Favicons with mimetype 'image/vnd.microsoft.icon' are not supported by IPX / sharp
// So we'll fetch it ourselves and cache it
const extractedFaviconUrl = targetUrl.match(/\/_\/(https:\/\/.*)/)
if (extractedFaviconUrl?.[1]) {
const rawFaviconResponse = await fetch(extractedFaviconUrl[1])
data = await rawFaviconResponse.blob()
}
}

if (response.ok) {
if (data.type.match(/^image/)) {
cache.set(targetUrl, data)
}

// TODO: Clone response body from raw retry to immediately return that
return new Response(response.body, {
status: response.status,
statusText: response.statusText
Expand Down

0 comments on commit c0f15c7

Please # to comment.