Skip to content

Commit b776d8c

Browse files
committed
it's working
1 parent 37d1393 commit b776d8c

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

worker/src/index.ts

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { DurableObject } from "cloudflare:workers";
22

3-
const RESPONSE_TIMEOUT = 30_000; // ms
3+
const RESPONSE_TIMEOUT_MS = 30_000; // 30 seconds
44

55
export class MyDurableObject extends DurableObject {
66
// TODO: think of using a WeakMap
@@ -34,6 +34,7 @@ export class MyDurableObject extends DurableObject {
3434
});
3535

3636
server.addEventListener("close", (cls: CloseEvent) => {
37+
this.reject?.(new Error("server closed"));
3738
console.info("closing connection", cls.code, cls.reason);
3839
server.close(1001, `server closed (${cls.code}: ${cls.reason})`);
3940
});
@@ -55,7 +56,6 @@ export class MyDurableObject extends DurableObject {
5556
url: request.url,
5657
headers: Object.fromEntries(request.headers.entries()),
5758
};
58-
5959
this.proxyTo.send(
6060
JSON.stringify({
6161
type: "request",
@@ -69,7 +69,7 @@ export class MyDurableObject extends DurableObject {
6969
this.resolve = resolve;
7070
this.reject = reject;
7171
}),
72-
RESPONSE_TIMEOUT,
72+
RESPONSE_TIMEOUT_MS,
7373
);
7474
} catch (error) {
7575
if (error instanceof TimeoutError) {
@@ -83,7 +83,28 @@ export class MyDurableObject extends DurableObject {
8383
}
8484

8585
message(event: MessageEvent): void {
86-
this.resolve?.(new Response(String(event.data)));
86+
if (typeof event.data !== "string") {
87+
console.error("message is not a string", typeof event.data);
88+
this.reject?.(new Error("message is not a string"));
89+
return;
90+
}
91+
92+
const message = JSON.parse(event.data);
93+
if (message.type === "response") {
94+
const { status, statusText, headers, body: body64 } = message.response;
95+
96+
const body = atob(body64);
97+
98+
this.resolve?.(
99+
new Response(body, {
100+
status,
101+
statusText,
102+
headers: new Headers(headers),
103+
}),
104+
);
105+
} else {
106+
this.reject?.(new Error("unknown message type"));
107+
}
87108
}
88109

89110
async close(): Promise<Response> {

0 commit comments

Comments
 (0)