| 1 | import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; |
| 2 | import * as Cloudflare from "alchemy/Cloudflare"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | import * as HttpRouter from "effect/http/HttpRouter"; |
| 6 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 7 | import { Auth } from "./auth.ts"; |
| 8 | import { AuthDb } from "./database.ts"; |
| 9 | import { HttpLive } from "./http.ts"; |
| 10 | |
| 11 | export default class AuthApi extends Cloudflare.Worker<AuthApi>()( |
| 12 | "AuthApi", |
| 13 | { |
| 14 | main: import.meta.url, |
| 15 | compatibility: { flags: ["nodejs_compat"] }, |
| 16 | assets: { directory: "./public" }, |
| 17 | }, |
| 18 | Effect.gen(function* () { |
| 19 | const auth = yield* Auth; |
| 20 | const http = yield* HttpRouter.toHttpEffect(HttpLive); |
| 21 | return { |
| 22 | fetch: Effect.gen(function* () { |
| 23 | const request = yield* HttpServerRequest; |
| 24 | const pathname = new URL(request.url, "http://localhost").pathname; |
| 25 | if (pathname === "/api/auth" || pathname.startsWith("/api/auth/")) { |
| 26 | return yield* auth.fetch; |
| 27 | } |
| 28 | return yield* http; |
| 29 | }), |
| 30 | }; |
| 31 | }).pipe(Effect.provide(Auth.layer.pipe(Layer.provide(CloudflareD1(AuthDb))))), |
| 32 | ) {} |