UNPKG

1.81 kBMarkdownView Raw
1# Deno Fetch Event Adapter
2
3Dispatches 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.~~
6This 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"
12import 'https://deno.land/x/fetch_event_adapter/listen.ts';
13
14// This module adds a global `FetchEvent`
15if (typeof FetchEvent !== 'undefined') console.log(true);
16
17// This module also adds global type declarations, s.t. this type-checks:
18self.addEventListener('fetch', event => {
19 const ip = event.request.headers.get('x-forwarded-for');
20 event.respondWith(new Response(`Hello ${ip ?? 'World'}`));
21});
22```
23
24Your script needs the `--allow-net` permissions. It also requires a `--location`,
25to know on which port to listen for incoming connections:
26
27```sh
28deno run --allow-net --location=http://localhost:8000 worker.js
29```
30
31If you set the `--location` to either HTTPS or port 443, you have to provide a `--cert` and a `--key` parameter.
32Your script will also need the read permission to read the files:
33
34```sh
35deno 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
41If 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
44self.addEventListener('error', event => {
45 console.warn(event.message);
46 console.warn(event.error);
47});
48```