1import * as Effect from "effect/Effect";
2import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
3import { BackendClient } from "./BackendClient";
4import { env } from "./Env";
5import { FrontendApi, Hello, KvOk, KvValue } from "./NextApi";
6
7const kvGet = (key: string) =>
8 Effect.tryPromise({
9 try: () => env.KV.get(key),
10 catch: (cause) => new Error(String(cause)),
11 }).pipe(Effect.orDie);
12
13const kvPut = (key: string, value: string) =>
14 Effect.tryPromise({
15 try: () => env.KV.put(key, value),
16 catch: (cause) => new Error(String(cause)),
17 }).pipe(Effect.orDie);
18
19export const FrontendHandlers = HttpApiBuilder.group(
20 FrontendApi,
21 "frontend",
22 Effect.fn(function* (handlers) {
23 const client = yield* BackendClient;
24
25 return handlers
26 .handle("hello", () =>
27 client.Backend.listNotes().pipe(
28 Effect.map(
29 (listed) =>
30 new Hello({
31 message: env.GREETING ?? "Hello from vinext!",
32 noteCount: listed.notes.length,
33 }),
34 ),
35 Effect.orDie,
36 ),
37 )
38 .handle("listNotes", () => client.Backend.listNotes().pipe(Effect.orDie))
39 .handle("createNote", ({ payload }) =>
40 client.Backend.createNote({ payload }).pipe(Effect.orDie),
41 )
42 .handle("deleteNote", ({ params }) =>
43 client.Backend.deleteNote({ params }).pipe(Effect.orDie),
44 )
45 .handle("getKv", ({ params }) =>
46 kvGet(params.key).pipe(Effect.map((value) => new KvValue({ value }))),
47 )
48 .handle("putKv", ({ params, payload }) =>
49 kvPut(params.key, payload).pipe(Effect.as(new KvOk({ ok: true }))),
50 );
51 }),
52);