import { query_getImages, query_getImage, query_saveImage } from "./database"; export function getImages(req: Request): Promise { return new Promise(async (resolve, reject) => { let images = query_getImages.all(); if (!images) { const ErrorResponse = new Response("No Images Found", { status: 404 }); resolve(ErrorResponse); } const imageList = await query_getImages.all(); console.log("imageList:", imageList); const response = Response.json({ images: imageList }); resolve(response); }); } export function getImage(req: Request): Promise { return new Promise(async (resolve, reject) => { const path = new URL(req.url).pathname; const entity = path.split("/")[2]; // images/1.png const imageID = entity.split(".")[0]; //1 let image: any = query_getImage.get(imageID); // DB Call if (!image) { const ErrorResponse = new Response("No Images Found", { status: 404 }); reject(ErrorResponse); } // Send image as response const base64Image = image.image; const buffer = Buffer.from(base64Image, "base64"); let response = new Response(new Blob([buffer]), { headers: { "Content-Type": image.type }, }); resolve(response); }); } export function saveImage(req: Request): Promise { const allowedFileTypes = ["image/png", "image/jpeg", "image/gif"]; return new Promise(async (resolve, reject) => { const formdata = await req.formData(); const image: Blob = formdata.get("image"); if (!image || allowedFileTypes.includes(image.type) === false) { const ErrorResponse = new Response("Did not recieve valid image", { status: 400, }); resolve(ErrorResponse); } // Transform image to storage format let buffer = await image.arrayBuffer(); let base64Image = Buffer.from(buffer).toString("base64"); // Save image to DB query_saveImage.get(base64Image, image.type); // buffer = Buffer.from(base64Image, "base64"); // // Testing getImage Logic as Well // let response = new Response(new Blob([buffer]), { // headers: { "Content-Type": image.type }, // }); // resolve(response); // Return Redirect(App Logic) resolve(Response.redirect("/")); }); }