added fetch image by id endpoint

This commit is contained in:
2026-01-12 18:59:02 +13:00
parent 760b2feb16
commit 6bde837330
2 changed files with 37 additions and 12 deletions

View File

@@ -0,0 +1,37 @@
import type { APIContext } from 'astro';
import { promises as fs } from 'fs';
import { join } from 'path';
import 'dotenv/config'
import { httpResponse } from '../../../utils/response';
const uploadDir = process.env.UPLOAD_DIR!;
export async function GET({ params }: APIContext) {
try {
const { id } = params
return readImage(id!)
} catch (error) {
return httpResponse({ error: `Failed to retrieve image: ${error}` }, 500);
}
}
async function readImage(id: string) {
const filepath = join(uploadDir, id);
try {
await fs.access(filepath);
} catch {
return httpResponse({ error: 'Image not found' }, 404);
}
const image = await fs.readFile(filepath);
const ext = id.split('.').pop()?.toLowerCase();
const contentType = ext === 'png' ? 'image/png' : 'image/jpeg';
return new Response(image, {
status: 200,
headers: {
'Content-Type': contentType,
}
});
}

View File

@@ -7,18 +7,6 @@ import 'dotenv/config'
const uploadDir = process.env.UPLOAD_DIR!;
export async function GET() {
try {
const files = await fs.readdir(uploadDir);
const images = files.filter(file =>
/\.(jpg|jpeg|png)$/i.test(file)
);
return httpResponse({ images }, 200);
} catch (error) {
return httpResponse({ error: `Failed to read images ${error}` }, 500);
}
}
export async function POST({ request }: APIContext) {
try {