Part 2: Add a Worker
You have a deployment with functions in it. Now add a Worker that calls them.
Bind a query
Section titled “Bind a query”import * as Cloudflare from "@alchemy.run/cloudflare";import * as Convex from "@alchemy.run/convex";import * as Effect from "effect/Effect";import * as HttpServerResponse from "effect/http/HttpServerResponse";import { Backend } from "./Backend.ts";import { ListMessages } from "./messages.ts";
export default class Api extends Cloudflare.Worker<Api>()( "Api", { main: import.meta.url }, Effect.gen(function* () { const list = yield* Convex.RunQuery(Backend);
return { fetch: Effect.gen(function* () { return yield* HttpServerResponse.json(yield* list(ListMessages, {})); }).pipe(Effect.orDie), }; }).pipe(Effect.provide(Convex.RunQueryHttp)),) {}list takes the declaration from part 1, so its arguments and result are typed. Convex.RunQuery grants nothing: the Worker gets the deployment’s URL, and public functions need no credentials.
Bind a mutation
Section titled “Bind a mutation”import { HttpServerRequest } from "effect/http/HttpServerRequest";import * as Layer from "effect/Layer";import { ListMessages } from "./messages.ts";import { AddMessage, ListMessages } from "./messages.ts";
Effect.gen(function* () { const list = yield* Convex.RunQuery(Backend); const add = yield* Convex.RunMutation(Backend);
return { fetch: Effect.gen(function* () { const request = yield* HttpServerRequest; if (request.method === "POST") { yield* add(AddMessage, { body: yield* request.text }); } return yield* HttpServerResponse.json(yield* list(ListMessages, {})); }).pipe(Effect.orDie), }; }).pipe(Effect.provide(Convex.RunQueryHttp)), }).pipe(Effect.provide(Layer.mergeAll(Convex.RunQueryHttp, Convex.RunMutationHttp))),POST adds a message, and every request lists them.
Add the Worker to your Stack
Section titled “Add the Worker to your Stack”import * as Cloudflare from "@alchemy.run/cloudflare";import * as Convex from "@alchemy.run/convex";import * as Alchemy from "alchemy";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import Api from "./src/Api.ts";import { Backend } from "./src/Backend.ts";
export default Alchemy.Stack( "CloudflareConvexWorkerExample", { providers: Layer.mergeAll(Cloudflare.providers(), Convex.providers()), state: Alchemy.localState(), }, Effect.gen(function* () { const deployment = yield* Backend; yield* Convex.Functions("Functions", { deployment, rootDir: "." }); const api = yield* Api; return { url: api.url.as<string>() }; }),);Deploy and try it
Section titled “Deploy and try it”pnpm alchemy deploybun alchemy deploynpx alchemy deployyarn alchemy deployPost a message to the Worker’s URL:
curl -X POST -d "hello" https://your-worker.workers.devThe response lists every message, including yours.