typescript-functional-extensions
Version:
A TypeScript implementation of synchronous and asynchronous Maybe and Result monads
32 lines (31 loc) • 1.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchJsonResponse = fetchJsonResponse;
exports.fetchResponse = fetchResponse;
const resultAsync_js_1 = require("./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
*/
function fetchJsonResponse(request, errorHandler) {
return resultAsync_js_1.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
*/
function fetchResponse(request, errorHandler) {
return resultAsync_js_1.ResultAsync.try(request, errorHandler).ensure((resp) => resp.ok, errorHandler);
}