diff --git a/src/main.ts b/src/main.ts index 92c7e18..f1ea663 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,25 +2,20 @@ import express from "express"; import cors from "cors"; import { FilesAPI } from "./routes/files"; import { PexelsAPI } from "./routes/pexels"; +import { WorkerAPI } from "./routes/worker"; const app = express(); const PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080; app.use( cors({ - origin: [ - "http://localhost:5173", - "http://localhost", - "https://localhost", - "capacitor://localhost", - "http://phoexatrips", - "https://phoexatrips", - ], + origin: ["http://localhost:5173", "http://localhost", "https://localhost", "capacitor://localhost"], }), ); app.use(FilesAPI); app.use(PexelsAPI); +app.use(WorkerAPI); const server = app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); diff --git a/src/routes/worker.ts b/src/routes/worker.ts new file mode 100644 index 0000000..2b2b2dc --- /dev/null +++ b/src/routes/worker.ts @@ -0,0 +1,8 @@ +import express, { Request, Response } from "express"; +import path from "path"; + +export const WorkerAPI = express.Router(); + +WorkerAPI.get("/serviceworker", (req: Request, res: Response) => { + res.sendFile(path.join(__dirname, "../../", "worker.js")); +}); diff --git a/worker.js b/worker.js new file mode 100644 index 0000000..4862e3c --- /dev/null +++ b/worker.js @@ -0,0 +1,24 @@ +const QUALITY = 0.75; + +self.addEventListener("message", async (event) => { + const { imageData } = event.data; + + try { + // Create an ImageBitmap from the image data + const imageBitmap = await createImageBitmap(imageData); + + const canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height); + const context = canvas.getContext("2d"); + + // Draw the ImageBitmap on the canvas + context.drawImage(imageBitmap, 0, 0, imageBitmap.width, imageBitmap.height); + + // Convert the canvas to a blob + const webpBlob = await canvas.convertToBlob({ type: "image/webp", quality: QUALITY }); + self.postMessage({ webpBlob }); + } catch (error) { + // Handle errors during image processing + console.error("Image conversion error:", error.message); + self.postMessage({ error: error.message }); + } +});