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
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
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
Parameters
- Function to lift. Any function returning a
ResponseLike
object.
- 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.