Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/eitherway/lib/adapters/web/fetch/mod.ts>liftFetch

Yet Another Option and Result Implementation - providing safe abstractions for fallible flows inspired by F# and Rust
Latest
function liftFetch
import { liftFetch } from "https://deno.land/x/eitherway@0.10.0/lib/adapters/web/fetch/mod.ts";

Use this to lift a fetch-like function into a Task context.

This is a constrained wrapper over Task.liftFallible and comes with a default ctorFn and errMapFn for the 2nd and 3rd parameter respectively.

Examples

Basic Usage

import { liftFetch } from "./mod.ts";

interface Company {
  name: string;
}

interface User {
  id: number;
  company: Company;
}

const lifted = liftFetch(fetch);
const resourceUrl = "https://jsonplaceholder.typicode.com/users/1";

const result: Company = await lifted(resourceUrl)
  .map(async (resp) => (await resp.json()) as User) // Lazy, use validation!
  .inspect(console.log)
  .inspectErr(console.error) // FailedRequest<Response> | FetchException
  .mapOr(user => user.company, { name: "Acme Corp." })
  .unwrap();

With custom Response type

import { liftFetch } from "./mod.ts";

interface Company {
  name: string;
}

interface User {
  id: number;
  company: Company;
}

interface UserResponse extends Response {
  json(): Promise<User>
}

function fetchUserById(id: number): Promise<UserResponse> {
  return fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
}

const lifted = liftFetch(fetchUserById);

const result: Company = await lifted(1)
  .map((resp) => resp.json()) // inferred as User
  .inspect(console.log)
  .inspectErr(console.error) // FailedRequest<UserResponse> | FetchException
  .mapOr(user => user.company, { name: "Acme Corp." })
  .unwrap();

Type Parameters

Args extends unknown[]
R extends ResponseLike
optional
T = R
optional
E1 = FailedRequest<R>
optional
E2 = FetchException

Parameters

fetchLike: (...args: Args) => R | PromiseLike<R>
  • Function to lift. Any function returning a ResponseLike object.
optional
ctorFn: (arg: R) => Result<T, E1> | PromiseLike<Result<T, E1>>
  • Result or Task constructor function. Use this to distinguish successful from failed requests.
optional
errMapFn: (cause: unknown) => E2
  • Error map function. Maps any exception to a known error.

Returns

(...args: Args) => Task<T, E1 | E2>