UNPKG

typescript-functional-extensions

Version:

A TypeScript implementation of synchronous and asynchronous Maybe and Result monads

28 lines (27 loc) 1.45 kB
import { ResultAsync } from './resultAsync.js'; /** * Wraps a fetch request generated Promise in a ResultAsync, * ensuring both connection errors and Http status code errors * are converted into failed Results. * The JSON response is unwrapped as object type specified by TValue. Use this for JSON responses. * @param request A Promise<Response> generated by a fetch() request * @param errorHandler Handles connection and Http status code errors. Can be asynchronous to enable evaluation of the Response body. * @returns ResultAsync representing the success/failure of the request */ export function fetchJsonResponse(request, errorHandler) { return ResultAsync.try(request, errorHandler) .ensure((resp) => resp.ok, errorHandler) .map((resp) => resp.json()); } /** * Wraps a fetch request generated Promise in a ResultAsync, * ensuring both connection errors and Http status code errors * are converted into failed Results. * The raw Response object is returned as the Result success value. * @param request A Promise<Response> generated by a fetch() request * @param errorHandler Handles connection and Http status code errors. Can be asynchronous to enable evaluation of the Response body. * @returns ResultAsync representing the success/failure of the request */ export function fetchResponse(request, errorHandler) { return ResultAsync.try(request, errorHandler).ensure((resp) => resp.ok, errorHandler); }