import type { Note } from "#domain/Note" import { Effect, Layer } from "effect" import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http" // A fake of the notes JSON API, answering `Notes.layerHttp`'s requests from // a Map. A test of the whole app swaps the platform's `HttpClient`, never // the domain services, so every component runs the code it ships with. // `Layer.sync` builds a fresh Map each time the Layer is built. Outside a // DOM environment a relative URL has no base, so the fake gives it one. export const NotesHttpFake = (seed: ReadonlyArray) => Layer.sync(HttpClient.HttpClient, () => { const notes = new Map(seed.map((note) => [note.id, note])) return HttpClient.make((request, url) => Effect.sync(() => { // `Notes.layerHttp` encodes the id as one path segment. const id = decodeURIComponent(url.pathname.slice("/api/notes/".length)) if (request.method === "PUT" && request.body._tag === "Uint8Array") { notes.set(id, JSON.parse(new TextDecoder().decode(request.body.body))) } const found = id === "" ? Array.from(notes.values()) : notes.get(id) return HttpClientResponse.fromWeb( request, found === undefined ? new Response(null, { status: 404 }) : Response.json(found) ) }) ).pipe( HttpClient.mapRequestInput( HttpClientRequest.prependUrl("http://notes.test") ) ) })