Fetch middleware for the modern minimalist.
yarn add fetch-run
import { Api } from 'fetch-run';
import * as uses from 'fetch-run/use';
const api = Api.create('https://example.org/api/v1');
if (__DEV__) {
api.use(uses.logger);
}
api.use(uses.error);
// Later in app
type LoginRes = { token: string };
type LoginReq = { email: string; password };
type User = { id: number; name: string };
api.post<LoginRes, LoginReq>('login', data);
api.get<User>(`users/${id}`).then((user) => {});
api.search<User[]>('users', { firstName: 'John' }).then((users) => {});
A simple implementation of the middleware pattern. It allows you to modify the Request object before your API call and use the Response object right after receiving the response from the server.
Here are some examples/implementations of the middleware pattern:
A good way to visualize the middleware pattern is to think of the Request/Response lifecycle as an onion. Every middleware added to the stack being a new onion layer on top of the previous one.
Every middleware takes a Request
in and must give a Response
out.
type Layer = (req: Request) => Promise<Response>;
type Middleware = (next: Layer) => Layer;
// src/http/my-middleware.ts
export const myMiddleware: Middleware =
(next: Layer) => async (req: Request) => {
// Before
const res: Response = await next(req);
// After
return res; // Response
};
Let's write a simple middleware that remembers an "access token" and sets a "Bearer header" on the next Request
once available.
// src/http/access-token.js
let accessToken;
export default (next) => async (req) => {
//
// BEFORE
// Modify/Use Request
//
if (accessToken) {
req.headers.set('Authorization', `Bearer ${accessToken}`);
}
const res = await next(req);
//
// AFTER
// Modify/Use Response
//
if (res.access_token) {
accessToken = res.access_token;
}
return res;
};
Since everything is a middleware, the order of execution is important.
Middlewares are executed in LIFO order ("Last In, First Out").
Everytime you push a new middleware to the stack, it is added as a new onion layer on top of all existing ones.
api.use(A);
api.use(B);
Execution order:
B
"Before" logicA
"Before" logic- (actual
fetch
call) A
"After" logicB
"After" logic
Note: B
is the most outer layer of the onion.
The library also exports an Http
flavour that does not transform the Response
to JSON.
import { Http } from 'fetch-run';
const http = new Http('https://example.org');
http.use(error);
http.get('index.html').then((res: Response) => {
// https://developer.mozilla.org/en-US/docs/Web/API/Response
res.blob();
res.formData();
res.json();
res.text();
// ...
});
Creates a new instance of Api
or Http
.
const api = new Api('', { credentials: 'include' });
const http = new Http('https://example.org', {
mode: 'no-cors',
headers: { 'X-Foo': 'Bar' },
});
Alternative & convenient way for creating an instance.
const api = Api.create('', { credentials: 'include' });
const http = Http.create('https://example.org', {
mode: 'no-cors',
headers: { 'X-Foo': 'Bar' },
});
Api.create
will add the following default headers:
{
"Accept": "application/json",
"Content-Type": "application/json"
}
new Api
, new Http
& Http.create
do not.
Adds a middleware to the stack. See Middlewares and Execution order (LIFO) for more information.
type Layer = (req: Request) => Promise<Response>;
type Middleware = (next: Layer) => Layer;
Performs a GET
request. If you need to pass query parameters to the URL, use search
instead.
Performs a GET
request with additional query parameters passed in URL.
Performs a POST
request.
type BodyData = FormData | object | void;
Performs a PUT
request.
Performs a PATCH
request.
Performs a DELETE
request.
All options
are merged with the default options (constructor
) and passed down to the Request
object.
- Catch HTTP responses with error status code (
< 200 || >= 300
– a.k.a.response.ok
) - Create a custom
err: HTTPError
- Set
err.code = res.status
- Set
err.message = res.statusText
- Set
err.request = req
- Set
err.response = res
- Throw
HTTPError
import { error } from 'fetch-run/use';
api.use(error);
Later in app:
import { HTTPError } from 'fetch-run';
try {
api.updateUser(123, { name: 'Tyron' });
} catch (err) {
if (err instanceof HTTPError) {
err.response.json(); //...
} else {
throw err;
}
}
All middlewares registered after the error
middleware, will not be executed (error
middleware throws).
This is why, for example, you need to register the logger
middleware first, so it can log req
& res
before the error is thrown.
The Metro bundler (React Native) fails with ENOENT
error when throwing a custom Error
:
Error: ENOENT: no such file or directory, open '<app-root>/HTTPError@http:/127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false'
This is why we need to throw a "normal" Error
and unfortunately not the custom HTTPError
itself (yet?).
This prevents the use of instanceof HTTPError
+ requires to assert the type when using Typescript:
import { HTTPError } from 'fetch-run';
try {
// ...
} catch (err: Error) {
// if (err instanceof HTTPError) // Cannot...
if (err.name === 'HTTPError') {
// Assert type...
(err as HTTPError).response.json(); // ...
}
}
See source code for more details.
import { errorMetro } from 'fetch-run/use';
api.use(errorMetro);
A simple Request
& Response
console logger for when you don't need (yet) the full Debug Remote JS capabilities.
import { logger } from 'fetch-run/use';
if (__DEV__) {
api.use(logger);
}
// Note: To register before `error` middleware (throws)
// api.use(error)
For example when used with Laravel Sanctum.
- Get
XSRF-TOKEN
cookie value - Set
X-XSRF-TOKEN
header
import { xsrf } from 'fetch-run/use';
api.use(xsrf);