Files
Lazuli/src/routes/api/remoteImage/+server.ts

28 lines
918 B
TypeScript
Raw Normal View History

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 MAX_TRIES = 3
2024-04-09 00:10:23 -04:00
2024-04-09 14:22:14 -04:00
const fetchImage = async (): Promise<ArrayBuffer> => {
let tryCount = 0
while (tryCount < MAX_TRIES) {
++tryCount
try {
return await fetch(imageUrl).then((response) => response.arrayBuffer())
} catch (error) {
console.error(error)
continue
}
}
throw new Error('Exceed Max Retires')
}
return new Response(await fetchImage())
2024-04-09 00:10:23 -04:00
}