Diffinery

homeflare/celldpublic

39 lines · 1.1 KBRaw History
1import { Container, getContainer, getRandom } from "@cloudflare/containers";
2
3export class MyContainer extends Container {
4 defaultPort = 8080;
5 sleepAfter = "2m";
6 envVars = { MESSAGE: "passed in by the Container class" };
7
8 onStart() {
9 console.log("container started");
10 }
11 onStop() {
12 console.log("container stopped");
13 }
14 onError(error) {
15 console.log("container error:", error);
16 }
17}
18
19export default {
20 async fetch(request, env) {
21 const { pathname } = new URL(request.url);
22 if (pathname.startsWith("/container/")) {
23 // One container per path: each name is its own object and process.
24 return getContainer(env.MY_CONTAINER, pathname).fetch(request);
25 }
26 if (pathname.startsWith("/lb")) {
27 // Spread requests over three containers.
28 const container = await getRandom(env.MY_CONTAINER, 3);
29 return container.fetch(request);
30 }
31 if (pathname.startsWith("/singleton")) {
32 return getContainer(env.MY_CONTAINER).fetch(request);
33 }
34 return new Response(
35 "Try /container/<name>, /lb, or /singleton\n",
36 { headers: { "content-type": "text/plain" } },
37 );
38 },
39};