2022-07-01 15:47:48 +00:00
|
|
|
// @ts-ignore
|
2022-07-01 20:06:01 +00:00
|
|
|
import type { APIRoute } from 'astro';
|
2022-07-01 15:47:48 +00:00
|
|
|
import etag from 'etag';
|
|
|
|
import { lookup } from 'mrmime';
|
2022-07-01 20:06:01 +00:00
|
|
|
import loader from 'virtual:image-loader';
|
2022-07-01 15:47:48 +00:00
|
|
|
import { isRemoteImage, loadRemoteImage } from '../utils.js';
|
|
|
|
|
|
|
|
export const get: APIRoute = async ({ request }) => {
|
|
|
|
try {
|
|
|
|
const url = new URL(request.url);
|
|
|
|
const transform = loader.parseTransform(url.searchParams);
|
|
|
|
|
|
|
|
if (!transform) {
|
|
|
|
return new Response('Bad Request', { status: 400 });
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Can we lean on fs to load local images in SSR prod builds?
|
2022-07-01 17:43:26 +00:00
|
|
|
const href = isRemoteImage(transform.src)
|
|
|
|
? new URL(transform.src)
|
|
|
|
: new URL(transform.src, url.origin);
|
2022-07-01 15:47:48 +00:00
|
|
|
|
|
|
|
const inputBuffer = await loadRemoteImage(href.toString());
|
|
|
|
|
|
|
|
if (!inputBuffer) {
|
|
|
|
return new Response(`"${transform.src} not found`, { status: 404 });
|
|
|
|
}
|
|
|
|
|
|
|
|
const { data, format } = await loader.transform(inputBuffer, transform);
|
|
|
|
|
|
|
|
return new Response(data, {
|
|
|
|
status: 200,
|
|
|
|
headers: {
|
|
|
|
'Content-Type': lookup(format) || '',
|
|
|
|
'Cache-Control': 'public, max-age=31536000',
|
2022-07-01 17:43:26 +00:00
|
|
|
ETag: etag(inputBuffer),
|
|
|
|
Date: new Date().toUTCString(),
|
|
|
|
},
|
2022-07-01 15:47:48 +00:00
|
|
|
});
|
|
|
|
} catch (err: unknown) {
|
|
|
|
return new Response(`Server Error: ${err}`, { status: 500 });
|
|
|
|
}
|
2022-07-01 17:43:26 +00:00
|
|
|
};
|