| 1 | import { Container } from "@cloudflare/containers"; |
| 2 | |
| 3 | /** |
| 4 | * Container-backed Durable Object class hosted by a Vite Worker (issue #997): |
| 5 | * the `Cloudflare.Container` declaration on the site's `env` is the DO |
| 6 | * namespace binding plus its ContainerApplication. `Container.fetch` starts |
| 7 | * the container on demand and forwards requests to the echo server listening |
| 8 | * on port 8080 inside it. |
| 9 | */ |
| 10 | export class EchoObject extends Container { |
| 11 | defaultPort = 8080; |
| 12 | } |
| 13 | |
| 14 | type EchoStub = { |
| 15 | fetch(request: Request): Promise<Response>; |
| 16 | }; |
| 17 | |
| 18 | type Env = { |
| 19 | ASSETS: { |
| 20 | fetch(request: Request): Promise<Response>; |
| 21 | }; |
| 22 | ECHO: { |
| 23 | getByName(name: string): EchoStub; |
| 24 | }; |
| 25 | }; |
| 26 | |
| 27 | export default { |
| 28 | async fetch(request: Request, env: Env): Promise<Response> { |
| 29 | const url = new URL(request.url); |
| 30 | |
| 31 | if (url.pathname === "/api/echo") { |
| 32 | return env.ECHO.getByName("vite-container-fixture").fetch(request); |
| 33 | } |
| 34 | |
| 35 | return env.ASSETS.fetch(request); |
| 36 | }, |
| 37 | }; |