0.2.2 • Published 8 months ago

worker-webserver v0.2.2

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

中文文档

worker-webserver

Worker-webserver is a lightweight NPM package that allows you to implement a web server in your service worker using the fetch event. It allows you to intercept incoming requests, match them with a user-defined router, and execute a series of middleware functions to handle them.

Installation

You can install worker-webserver via NPM using the following command:

npm install worker-webserver --save

Usage

Export sw.js using the CLI command and place it in your static resource directory. If you are using Vite or Umi, it corresponds to the public folder

npx worker-webserver --out public

First, import the necessary functions and interfaces:

import { App, Route } from 'worker-webserver'

Then, create an array of custom routes to match incoming requests:

const customRoutes: Route[] = [
  {
    path: "/users/:id",
    method: "POST",
    handler: async (ctx) => {
      ctx.res.body = JSON.stringify({
        test: "test",
        ...ctx.params,
      });
      ctx.res.headers.set("content-type", "application/json");
    },
  },
];

You can define your own middleware functions to handle incoming requests and responses. For example:

const app = new App();

app.addRoutes(customRoutes);


app.use(async (ctx, next) => {
  await next();

  // unified code to 200
  if (ctx.res.body) {
    const contentType = ctx.res.headers.get("content-type");
    if (contentType === "application/json") {
      try {
        let body = JSON.parse(ctx.res.body);
        if (body.code) {
          body.code = 200;
        }
        ctx.res.body = JSON.stringify(body);
      } catch {}
    }
  }
});

Finally, start the worker-webserver by calling the start() function.

app.start();

You can also stop the worker-webserver by calling the stop() function.

app.stop();

That's it! You can now intercept incoming requests, match them with a user-defined router, and execute middleware functions to handle them.

0.1.8

12 months ago

0.1.7

12 months ago

0.2.2

8 months ago

0.1.3

12 months ago

0.1.6

12 months ago

0.1.2

12 months ago

0.1.1

12 months ago

0.0.7

12 months ago

0.0.5

12 months ago

0.0.4

12 months ago

0.0.3

12 months ago

0.0.2

12 months ago

0.0.1

12 months ago