| 1 | import * as Cloudflare from "alchemy/Cloudflare"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Redacted from "effect/Redacted"; |
| 4 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 5 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 6 | import { ApiKey } from "./ApiKey.ts"; |
| 7 | |
| 8 | export default class Api extends Cloudflare.Worker<Api>()( |
| 9 | "Api", |
| 10 | { |
| 11 | main: import.meta.url, |
| 12 | }, |
| 13 | Effect.gen(function* () { |
| 14 | const apiKey = yield* Cloudflare.SecretsStore.ReadSecret(ApiKey); |
| 15 | |
| 16 | return { |
| 17 | fetch: Effect.gen(function* () { |
| 18 | const request = yield* HttpServerRequest; |
| 19 | |
| 20 | if (request.url === "/secret") { |
| 21 | const value = Redacted.value(yield* apiKey); |
| 22 | const masked = value.slice(0, 4) + "****"; |
| 23 | return HttpServerResponse.text(`Secret (masked): ${masked}`); |
| 24 | } |
| 25 | |
| 26 | return HttpServerResponse.text( |
| 27 | "Hello from Cloudflare Secrets Store example!", |
| 28 | ); |
| 29 | }).pipe( |
| 30 | Effect.catchTag("SecretError", (err) => |
| 31 | Effect.succeed( |
| 32 | HttpServerResponse.text(`Failed to read secret: ${err.message}`, { |
| 33 | status: 500, |
| 34 | }), |
| 35 | ), |
| 36 | ), |
| 37 | ), |
| 38 | }; |
| 39 | }).pipe(Effect.provide(Cloudflare.SecretsStore.ReadSecretBinding)), |
| 40 | ) {} |