With Axios I was able to use a Request Interceptor where I could add arbitrary data to the request object and then retrieve it in the response's reference to thus request object.
With ofetch, I don't see an option to add and later read custom (internal) data without actually sending it in the URL.
Found a solution.
You can define custom extra data which you can append to the request object via the onRequest
interceptor method and then read later in onResponse
when creating the ofetch instance.
const fetchClient = ofetch.create({
onRequest: ({ options }) => {
options._startTime = Date.now();
},
onResponse: ({ options, response }) => {
const duration = Date.now() - options.startTime;
console.debug(`Response time for '${response.url}: ${duration}ms'`);
},
});
For TypeScript support, you can add custom module declaration (overrides), e.g. in the same file, like so:
declare module 'ofetch' {
type ApiFetchOptionsExtra = {
_startTime?: number
}
interface ResolvedFetchOptions extends ApiFetchOptionsExtra {}
interface FetchOptions extends ApiFetchOptionsExtra {}
}