fetch wrapper for api calls

Hello people, I have struggling with creating a nice wrapper around $fetch from a long time now. Here is a complete overview of what I want. A function that I can use for authenticated requests and when a request gives unauthorized error (401) means the current auth token is expired then I want to call refresh token api and update the auth token, retry the previous request with new token. Here is what I have been able to come up with:
type Request = Parameters<typeof $fetch>[0];

type ExtendedFetchOptions = Parameters<typeof $fetch>[1] & {
authToken: string;
refreshTokens: () => Promise<string>;
};

export default async function authorizedRequest<T>(
request: Request,
options: ExtendedFetchOptions,
): Promise<API_Response<T>> {
try {
const response = await $fetch<API_Response<T>>(request, {
...options,
headers: {
...options?.headers,
Authorization: options.authToken,
},
baseURL: useRuntimeConfig().public.baseURL,
});
return response;
} catch (fetchError: any) {
if (fetchError.statusCode == constants.STATUS_UNAUTHORIZED) {
try {
const newToken = await options.refreshTokens();
options.authToken = newToken;
return authorizedRequest(request, options);
} catch (refreshTokenError: any) {
throw refreshTokenError;
}
}
throw fetchError;
}
}
type Request = Parameters<typeof $fetch>[0];

type ExtendedFetchOptions = Parameters<typeof $fetch>[1] & {
authToken: string;
refreshTokens: () => Promise<string>;
};

export default async function authorizedRequest<T>(
request: Request,
options: ExtendedFetchOptions,
): Promise<API_Response<T>> {
try {
const response = await $fetch<API_Response<T>>(request, {
...options,
headers: {
...options?.headers,
Authorization: options.authToken,
},
baseURL: useRuntimeConfig().public.baseURL,
});
return response;
} catch (fetchError: any) {
if (fetchError.statusCode == constants.STATUS_UNAUTHORIZED) {
try {
const newToken = await options.refreshTokens();
options.authToken = newToken;
return authorizedRequest(request, options);
} catch (refreshTokenError: any) {
throw refreshTokenError;
}
}
throw fetchError;
}
}
Please review this and provide your valuable advice. Another thing that I have struggled with a lot is use of useAsyncData or useFetch for requests that don’t involve reactive values. These requests can be signup, login or requests that are needed to be sent on some user action. How should I use my fetch wrapper should I use it with useAsyncData for a much nicer error handling or use try catch Thank you very much
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server