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-22 23:01:56 +00:00
|
|
|
import { fileURLToPath } from 'url';
|
2022-07-01 20:24:45 +00:00
|
|
|
// @ts-ignore
|
2022-07-01 20:06:01 +00:00
|
|
|
import loader from 'virtual:image-loader';
|
2022-07-22 23:01:56 +00:00
|
|
|
import { isRemoteImage, loadLocalImage, loadRemoteImage } from '../utils/images.js';
|
2022-07-01 15:47:48 +00:00
|
|
|
|
|
|
|
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 });
|
|
|
|
}
|
|
|
|
|
2022-07-22 23:01:56 +00:00
|
|
|
let inputBuffer: Buffer | undefined = undefined;
|
2022-07-01 15:47:48 +00:00
|
|
|
|
2022-07-22 23:01:56 +00:00
|
|
|
if (isRemoteImage(transform.src)) {
|
|
|
|
inputBuffer = await loadRemoteImage(transform.src);
|
|
|
|
} else {
|
|
|
|
const pathname = fileURLToPath(new URL(`../client${transform.src}`, import.meta.url));
|
|
|
|
inputBuffer = await loadLocalImage(pathname);
|
|
|
|
}
|
2022-07-01 15:47:48 +00:00
|
|
|
|
|
|
|
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
|
|
|
};
|