From 6bde837330be89a5c1c38412fd234b04cc2a2317 Mon Sep 17 00:00:00 2001 From: June Date: Mon, 12 Jan 2026 18:59:02 +1300 Subject: [PATCH] added fetch image by id endpoint --- src/pages/api/image/[id].ts | 37 ++++++++++++++++++++++++++++++++++++ src/pages/api/image/index.ts | 12 ------------ 2 files changed, 37 insertions(+), 12 deletions(-) create mode 100644 src/pages/api/image/[id].ts diff --git a/src/pages/api/image/[id].ts b/src/pages/api/image/[id].ts new file mode 100644 index 0000000..8345ba3 --- /dev/null +++ b/src/pages/api/image/[id].ts @@ -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, + } + }); +} \ No newline at end of file diff --git a/src/pages/api/image/index.ts b/src/pages/api/image/index.ts index acaa066..0e5d1d9 100644 --- a/src/pages/api/image/index.ts +++ b/src/pages/api/image/index.ts @@ -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 {