binding.ts
This file
Path
packages/project/src/code-store/binding.ts
57 lines · 1.7 KiB · TypeScript
Last changed by
Merge build/comments-project into mainoscabrielbefore adoption49efd2a
History of this fileTake it
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import { Data, Effect, Layer, Option } from "effect";
import { CodeStore, fittingKey } from "../code-store.ts";import type { CodeStoreApi } from "../code-store.ts";
/** Structural, so the package needs no Workers types. */export interface BucketLike { readonly get: ( key: string ) => Promise<{ readonly text: () => Promise<string> } | null>; readonly put: ( key: string, value: string ) => Promise<{ readonly key: string } | null>;}
class CodeStoreUnreachable extends Data.TaggedError("CodeStoreUnreachable")<{ readonly cause: unknown;}> {}
const reach = <A>(run: () => Promise<A>) => Effect.tryPromise({ catch: (cause) => new CodeStoreUnreachable({ cause }), try: run, });
export const CodeStoreR2 = (bucket: BucketLike) => { const store: CodeStoreApi = { get: (key) => Effect.flatMap(fittingKey(key), (fit) => reach(() => bucket.get(fit)).pipe( Effect.flatMap((found) => found === null ? Effect.succeedNone : Effect.asSome(reach(() => found.text())) ), Effect.catchTag("CodeStoreUnreachable", ({ cause }) => Effect.as( Effect.logWarning(`the code store could not read ${fit}`, cause), Option.none<string>() ) ) ) ), put: (key, value) => Effect.flatMap(fittingKey(key), (fit) => reach(() => bucket.put(fit, value)).pipe( Effect.asVoid, Effect.catchTag("CodeStoreUnreachable", ({ cause }) => Effect.logWarning(`the code store could not keep ${fit}`, cause) ) ) ), };
return Layer.succeed(CodeStore, store);};