2024-04-09 00:10:23 -04:00
|
|
|
import type { RequestHandler } from '@sveltejs/kit'
|
|
|
|
|
|
2024-04-09 14:22:14 -04:00
|
|
|
// This endpoint exists to act as a proxy for images, bypassing any CORS or other issues
|
|
|
|
|
// that could arise from using images from another origin
|
2024-04-09 00:10:23 -04:00
|
|
|
export const GET: RequestHandler = async ({ url }) => {
|
|
|
|
|
const imageUrl = url.searchParams.get('url')
|
2024-04-09 14:22:14 -04:00
|
|
|
if (!imageUrl || !URL.canParse(imageUrl)) return new Response('Missing or invalid url parameter', { status: 400 })
|
2024-04-09 00:10:23 -04:00
|
|
|
|
2024-04-09 14:22:14 -04:00
|
|
|
const fetchImage = async (): Promise<ArrayBuffer> => {
|
2024-04-13 00:45:35 -04:00
|
|
|
const MAX_TRIES = 3
|
|
|
|
|
let tries = 0
|
|
|
|
|
while (tries < MAX_TRIES) {
|
|
|
|
|
++tries
|
|
|
|
|
const response = await fetch(imageUrl).catch((reason) => {
|
|
|
|
|
console.error(`Image fetch to ${imageUrl} failed: ${reason}`)
|
|
|
|
|
return null
|
|
|
|
|
})
|
|
|
|
|
if (!response || !response.ok) continue
|
|
|
|
|
|
|
|
|
|
const contentType = response.headers.get('content-type')
|
|
|
|
|
if (!contentType || !contentType.startsWith('image')) throw new Error(`Url ${imageUrl} does not link to an image`)
|
|
|
|
|
|
|
|
|
|
return await response.arrayBuffer()
|
2024-04-09 14:22:14 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new Error('Exceed Max Retires')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return new Response(await fetchImage())
|
2024-04-09 00:10:23 -04:00
|
|
|
}
|