The /api
module exports a fetcher
factory that can be used to create a send
function to make requests. The factory can be configured heavily to fit your needs, it accepts an object that can contain the following properties:
prepare
- a function that is called before the request is sent, it receives the specifiedmethod
andto
url string, and optionally abody
,from
URL, andheaders
object. It should prepare and return an object that satisfies theRequestInit
interfaceintercept
- a function that is called against theurl
string before the request is sentsweep
- a function that is called whenfetch
throws an error, it receives the thrown exception and returns a stringtransform
- a function that is called whenfetch
returns a response, it receives the response and can return anything that will used as thepayload
, defaults tor.json().catch(() => ({}))
exit
- a function that is called after the response is transformed, it receives a clone of the initial response and thepayload
, and should return a string if the request was unsuccessful, or anything falsy such asvoid | false | null | undefined
if it was successful
import { fetcher, type SendOptions } from 'mauss/api';
const send = fetcher({
prepare({ method, to, body }) {
// ... do some checks or logging
return {
method: method || 'GET',
mode: 'cors',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
};
},
exit({ status }, payload) {
if (status >= 500) return 'ServerError';
if (status >= 400) return 'ClientError';
// void or non-string means successful
},
});
// use the `send` function above to make and export an abstraction
export const API = {
// use getter to determine the template and infer the defined parameters
get 'session/:id'() {
// `tsf` function from 'mauss/std'
const render = tsf('https://auth.example/{id}/login');
return (params: Parameters<typeof render>[0], options: SendOptions = {}) => {
const target = send(render(params), options);
return {
// ... abstraction methods, for example
async post() {
return await target.post();
},
};
};
},
};