Skip to content

Commit

Permalink
feat: add serviceworker
Browse files Browse the repository at this point in the history
  • Loading branch information
Myphz committed Jan 2, 2024
1 parent 72d4fab commit 3e76254
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 8 deletions.
11 changes: 3 additions & 8 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand Down
8 changes: 8 additions & 0 deletions src/routes/worker.ts
Original file line number Diff line number Diff line change
@@ -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"));
});
24 changes: 24 additions & 0 deletions worker.js
Original file line number Diff line number Diff line change
@@ -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 });
}
});

0 comments on commit 3e76254

Please sign in to comment.