added fetch image by id endpoint
This commit is contained in:
37
src/pages/api/image/[id].ts
Normal file
37
src/pages/api/image/[id].ts
Normal 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,
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user