import { HttpRouter, HttpServerRequest, HttpServerResponse } from "@effect/platform"; import { Cause, Context, Data, Effect, Layer, Ref, Schema } from "effect"; const NonEmptyString = Schema.NonEmptyString; const Todo = Schema.Struct({ id: Schema.String, title: NonEmptyString, completed: Schema.Boolean, createdAt: Schema.String, updatedAt: Schema.String, }); export type Todo = typeof Todo.Type; const CreateTodoRequest = Schema.Struct({ title: NonEmptyString, completed: Schema.optional(Schema.Boolean), }); type CreateTodoRequest = typeof CreateTodoRequest.Type; const UpdateTodoRequest = Schema.Struct({ title: Schema.optional(NonEmptyString), completed: Schema.optional(Schema.Boolean), }).pipe( Schema.filter((input) => "title" in input || "completed" in input, { message: () => "update requires at least one of title or completed", }), ); type UpdateTodoRequest = typeof UpdateTodoRequest.Type; class TodoNotFound extends Data.TaggedError("TodoNotFound")<{ readonly id: string }> {} const now = () => new Date().toISOString(); const mockTodos = (): ReadonlyArray => { const timestamp = now(); return [ { id: "1", title: "Learn Effect", completed: true, createdAt: timestamp, updatedAt: timestamp }, { id: "2", title: "Build a Bun HTTP API", completed: false, createdAt: timestamp, updatedAt: timestamp, }, { id: "3", title: "Ship todo CRUD", completed: false, createdAt: timestamp, updatedAt: timestamp, }, ]; }; class TodoRepository extends Context.Tag("TodoRepository")< TodoRepository, { readonly list: Effect.Effect>; readonly get: (id: string) => Effect.Effect; readonly create: (input: CreateTodoRequest) => Effect.Effect; readonly update: (id: string, input: UpdateTodoRequest) => Effect.Effect; readonly delete: (id: string) => Effect.Effect; } >() {} export const TodoRepositoryLive = Layer.effect( TodoRepository, Effect.gen(function* () { const todos = yield* Ref.make(new Map(mockTodos().map((todo) => [todo.id, todo]))); const get = (id: string) => Ref.get(todos).pipe( Effect.flatMap((store) => { const todo = store.get(id); return todo ? Effect.succeed(todo) : Effect.fail(new TodoNotFound({ id })); }), Effect.withSpan("TodoRepository.get", { attributes: { id } }), ); return TodoRepository.of({ list: Ref.get(todos).pipe( Effect.map((store) => Array.from(store.values())), Effect.withSpan("TodoRepository.list"), ), get, create: (input) => Effect.gen(function* () { const timestamp = now(); const todo: Todo = { id: crypto.randomUUID(), title: input.title, completed: input.completed ?? false, createdAt: timestamp, updatedAt: timestamp, }; yield* Ref.update(todos, (store) => new Map(store).set(todo.id, todo)); return todo; }).pipe(Effect.withSpan("TodoRepository.create")), update: (id, input) => Effect.gen(function* () { const existing = yield* get(id); const updated: Todo = { ...existing, ...input, updatedAt: now(), }; yield* Ref.update(todos, (store) => new Map(store).set(id, updated)); return updated; }).pipe(Effect.withSpan("TodoRepository.update", { attributes: { id } })), delete: (id) => Effect.gen(function* () { yield* get(id); yield* Ref.update(todos, (store) => { const next = new Map(store); next.delete(id); return next; }); }).pipe(Effect.withSpan("TodoRepository.delete", { attributes: { id } })), }); }), ); const json = (body: unknown, status = 200) => HttpServerResponse.json(body, { status }); const noContent = HttpServerResponse.empty({ status: 204 }); const badRequest = (message: string) => json({ error: "BadRequest", message }, 400); const notFound = (id: string) => json({ error: "TodoNotFound", message: `Todo ${id} was not found` }, 404); const internalServerError = json( { error: "InternalServerError", message: "Unexpected server error" }, 500, ); const handleFailure = (cause: Cause.Cause) => { const failure = Cause.failureOption(cause); if (failure._tag === "Some") { const error = failure.value; if (error instanceof TodoNotFound) { return notFound(error.id); } return badRequest(String(error)); } return internalServerError; }; const withErrors = (effect: Effect.Effect) => effect.pipe(Effect.catchAllCause((cause) => handleFailure(cause))); const routeId = Effect.gen(function* () { const params = yield* HttpRouter.params; const id = params.id; if (!id) { return yield* Effect.fail("Missing todo id"); } return id; }); export const App = HttpRouter.empty.pipe( HttpRouter.get( "/todos", withErrors( Effect.gen(function* () { const repository = yield* TodoRepository; const todos = yield* repository.list; return yield* json(todos); }), ), ), HttpRouter.get( "/todos/:id", withErrors( Effect.gen(function* () { const repository = yield* TodoRepository; const id = yield* routeId; const todo = yield* repository.get(id); return yield* json(todo); }), ), ), HttpRouter.post( "/todos", withErrors( Effect.gen(function* () { const repository = yield* TodoRepository; const input = yield* HttpServerRequest.schemaBodyJson(CreateTodoRequest); const todo = yield* repository.create(input); return yield* json(todo, 201); }), ), ), HttpRouter.patch( "/todos/:id", withErrors( Effect.gen(function* () { const repository = yield* TodoRepository; const id = yield* routeId; const input = yield* HttpServerRequest.schemaBodyJson(UpdateTodoRequest); const todo = yield* repository.update(id, input); return yield* json(todo); }), ), ), HttpRouter.del( "/todos/:id", withErrors( Effect.gen(function* () { const repository = yield* TodoRepository; const id = yield* routeId; yield* repository.delete(id); return noContent; }), ), ), );