This function returns a Promise with an interface that contains two objects, within that function I have a fetch request where I return that interface.
The interface contains two objects called data and default, where data is the fetch response either json(), arraybuffer(), etc. default is the complete object of the fetch Response.
Everything goes in order when the Promise is resolved when the response is ok. But in addition, there is a property that I receive in the function that indicates that the function has to be executed again in case there is a 401 error (or any other outside of ok), this property is of type Array which can receive status codes where the request needs to be retried.
export function request(url: RequestInfo, options: IOptions): Promise<IResponse> {
// more code;
var defaults;
var response: IResponse;
return new Promise<IResponse>((resolve, reject) => {
fetch(url, {
method: options?.method ?? "get",
headers: headersInit,
body: options.data,
})
.then((resp) => {
defaults = resp;
if (resp.ok) {
if (utils.IsNullOrUndefined(options.result)) {
return resp.json();
} else {
switch (options.result) {
case "json":
return resp.json();
break;
case "arrayBuffer":
return resp.arrayBuffer();
break;
case "blob":
return resp.blob();
break;
case "text":
return resp.text();
break;
}
}
} else {
if(options.retryOn){
if(Array.isArray(options.retryOn) && options.retryOn.indexOf(resp.status) !== -1){
// Here I try to execute the function in case retryOn contains the status code that returned fetch
response = null;
defaults = null;
return request(url, options);
}
}
else {
response = {
data: null,
default: defaults,
};
reject(response);
}
}
})
.then((res) => {
response = {
data: res,
default: defaults,
};
resolve(response);
});
});
}
When the request returns an ok code, the Promise has the following fields as objects:
But if there was a status code other than ok, and in retryOn the required status code is found, the function is executed again and the following objects return.
The data object is duplicated
I run the function like this:
request("URL", {
method: "get",
retryOn: [401]
}).then(response => {
console.log(response.data);
console.log(response.default);
}).catch(error => {
console.log(error);
})