import {HttpMessage} from "@http4t/core/contract"; import {header} from "@http4t/core/headers"; import {bodyJson, jsonBody} from "@http4t/core/json"; import {success} from "@http4t/result"; import {MessageLens, routeFailed, RoutingResult} from "../lenses"; /** * NB: does not _check_ `Content-Type` header when extracting, but does * _set_ it when injecting * * Uses {@link JsonBody} to avoid deserialising twice. */ export class JsonLens implements MessageLens { async get(message: HttpMessage): Promise> { try { const value = await bodyJson(message.body); return success(value); } catch (e: any) { return routeFailed(`Expected valid json${e.message ? `- ${e.message}` : ""}`, ["body"]) } } async set(into: SetInto, value: T): Promise { return { ...into, headers: [...into.headers, header('Content-Type', 'application/json')], body: jsonBody(value) }; } } export function json(): MessageLens { return new JsonLens(); }