fetch + interceptors

Joshua Amaju - Aug 28 - - Dev Community

Intro

I often reach for HTTP libraries like axios to achieve features like intercepting request and response for things like attaching request token and refreshing authentication token. But we can still achieve the same result staying true to the native fetch API.

Setup

npm i fetch-prime
Enter fullscreen mode Exit fullscreen mode

Code

// features/users.ts
import {pipe} from "fp-ts/function";
import * as E from "fp-ts/Either";

import {chain as andThen} from "fetch-prime";
import {fetch, andThen, Fetch} from "fetch-prime/Fetch";
import * as Response from "fetch–prime/Response";

export function getUser(user: string) {
  return (adapter: Fetch) => {
    const res = await fetch(`/users/${user}`)(adapter);
    const ok = andThen(res.response, Response.filterStatusOk);
    const users = await andThen(ok, res => res.json());
    return users;
  }
}
Enter fullscreen mode Exit fullscreen mode

or a simple option

export function getUser(user: string) {
  return (adapter: Fetch) => {
    const res = await fetch(`/users/${user}`)(adapter);
    const users = await res.ok(res => res.json());
    return users;
  }
}
Enter fullscreen mode Exit fullscreen mode
// main.ts
import {pipe} from "fp-ts/function";

import Fetch from "fetch-prime/Adapters/Platform";
import * as Interceptor from "fetch-prime/Interceptor";
import BaseURL from "fetch-prime/Interceptors/Url";

import {getUsers} from "./features/users";

// ...

const baseURL = "https://myapi.io/api";

const interceptors = Interceptor.add(Interceptor.empty(), BaseURL(baseURL))

const interceptor = Interceptor.make(interceptors);

const adapter = interceptor(Fetch);

const users = await getUser(user_id)(adapter);
Enter fullscreen mode Exit fullscreen mode

Writing your own interceptor

import {pipe} from "fp-ts/function";
import * as Interceptor from "fetch-prime/Interceptor";
import { HttpRequest } from "fetch-prime/Request";

const TokenInterceptor = function (chain: Interceptor.Chain) {
  const { url, init } = chain.request.clone();
  const headers = new Headers(init?.headers);
  headers.set("Authorization", `Token ${token}`);
  return chain.proceed(new HttpRequest(url, { ...init, headers}));
};

// ...

const interceptors = pipe(
  Interceptor.empty(),
  Interceptor.add(BaseURL("https://myapi.io/api")),
  Interceptors.add(TokenInterceptor)
);
Enter fullscreen mode Exit fullscreen mode

You can find fetch-prime here. Please give it a star.

. . . . . . . . . . . . .
Terabox Video Player