import {HttpMessage} from "@http4t/core/contract"; import {header} from "@http4t/core/headers"; import {success} from "@http4t/result"; import {MessageLens, RoutingResult} from "../lenses"; import {bufferText, typeDescription} from "@http4t/core/bodies"; /** * NB: does not _check_ `Content-Type` header when extracting, but does * _set_ it when injecting * */ export class TextLens implements MessageLens { async get(message: TMessage): Promise> { return success(await bufferText(message.body)); } async set(into: SetInto, value: string): Promise { if (typeof value !== "string") throw new Error(`Expected a string but got ${value} (${typeDescription(value)})`) return { ...into, headers: [...into.headers, header('Content-Type', 'text/plain')], body: value }; } } export function text(): TextLens { return new TextLens(); }