| 1 | import * as Cloudflare from "alchemy/Cloudflare"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 4 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 5 | import { CloudflareD1 } from "../../../src/CloudflareD1.ts"; |
| 6 | import { BetterAuth } from "../../../src/index.ts"; |
| 7 | |
| 8 | export const Db = Cloudflare.D1.Database("BetterAuthDb"); |
| 9 | |
| 10 | export default class AuthWorker extends Cloudflare.Worker<AuthWorker>()( |
| 11 | "BetterAuthD1Worker", |
| 12 | { |
| 13 | main: import.meta.url, |
| 14 | compatibility: { |
| 15 | date: "2026-03-17", |
| 16 | flags: ["nodejs_compat"], |
| 17 | }, |
| 18 | }, |
| 19 | Effect.gen(function* () { |
| 20 | const auth = yield* BetterAuth({ |
| 21 | basePath: "/auth", |
| 22 | emailAndPassword: { enabled: true }, |
| 23 | }); |
| 24 | |
| 25 | return { |
| 26 | fetch: Effect.gen(function* () { |
| 27 | const request = yield* HttpServerRequest; |
| 28 | if (request.url.startsWith("/auth")) { |
| 29 | return yield* auth.fetch; |
| 30 | } |
| 31 | if (request.url.startsWith("/me")) { |
| 32 | const session = yield* auth |
| 33 | .getSession() |
| 34 | .pipe( |
| 35 | Effect.catchTag("BetterAuthApiError", () => Effect.succeed(null)), |
| 36 | ); |
| 37 | return yield* HttpServerResponse.json({ |
| 38 | email: session?.user.email ?? null, |
| 39 | }); |
| 40 | } |
| 41 | return HttpServerResponse.text("ok"); |
| 42 | }), |
| 43 | }; |
| 44 | }).pipe(Effect.provide(CloudflareD1(Db))), |
| 45 | ) {} |