1 | # Deno Fetch Event Adapter
|
2 |
|
3 | Dispatches global `fetch` events using Deno's [native HTTP server](https://deno.com/blog/v1.9#native-http%2F2-web-server).
|
4 |
|
5 | ~~It is mostly intended as a temporary solution until Deno [implements the Service Worker spec](https://github.com/denoland/deno/issues/5957#issuecomment-722568905) directly.~~
|
6 | This has been scrapped, but this module works just fine for local testing, developing Cloudflare Workers while offline, and similar use cases.
|
7 |
|
8 | ## Example
|
9 |
|
10 | ```ts
|
11 | // filename: "worker.js"
|
12 | import 'https://deno.land/x/fetch_event_adapter/listen.ts';
|
13 |
|
14 | // This module adds a global `FetchEvent`
|
15 | if (typeof FetchEvent !== 'undefined') console.log(true);
|
16 |
|
17 | // This module also adds global type declarations, s.t. this type-checks:
|
18 | self.addEventListener('fetch', event => {
|
19 | const ip = event.request.headers.get('x-forwarded-for');
|
20 | event.respondWith(new Response(`Hello ${ip ?? 'World'}`));
|
21 | });
|
22 | ```
|
23 |
|
24 | Your script needs the `--allow-net` permissions. It also requires a `--location`,
|
25 | to know on which port to listen for incoming connections:
|
26 |
|
27 | ```sh
|
28 | deno run --allow-net --location=http://localhost:8000 worker.js
|
29 | ```
|
30 |
|
31 | If you set the `--location` to either HTTPS or port 443, you have to provide a `--cert` and a `--key` parameter.
|
32 | Your script will also need the read permission to read the files:
|
33 |
|
34 | ```sh
|
35 | deno run --allow-net --allow-read --location=https://localhost:8000 worker.js \
|
36 | --cert=./path/to/cert.pem \
|
37 | --key=./path/to/key.pem
|
38 | ```
|
39 |
|
40 | ## Error Handling
|
41 | If an error occurs during estabslishing a connection (e.g. invalid certificate, etc...), the error is dispatched as a global `error` event rather then crashing the process. You can add custom logging like this:
|
42 |
|
43 | ```ts
|
44 | self.addEventListener('error', event => {
|
45 | console.warn(event.message);
|
46 | console.warn(event.error);
|
47 | });
|
48 | ```
|