Вот пример реализации на TypeScript:
interface RequestOptions {
headers?: { [key: string]: string };
abort?: () => void;
}
interface RequestConfig {
url: string;
options: RequestOptions;
}
class Request {
private url: string;
private options: RequestOptions;
constructor(url: string, options: RequestOptions) {
this.url = url;
this.options = options;
}
get() {
return this;
}
query(params: { [key: string]: string }) {
const queryString = Object.entries(params)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join("&");
this.url += `?${queryString}`;
return this;
}
cache(ms: number) {
const cacheKey = `cache:${this.url}`;
const cachedResponse = sessionStorage.getItem(cacheKey);
if (cachedResponse) {
return Promise.resolve(new Response(cachedResponse));
}
const originalThen = this.options.abort;
this.options.abort = () => {
clearTimeout(timer);
sessionStorage.removeItem(cacheKey);
originalThen && originalThen();
};
const timer = setTimeout(() => {
sessionStorage.removeItem(cacheKey);
}, ms);
return this;
}
retry(times: number) {
let retries = 0;
const originalThen = this.options.abort;
this.options.abort = () => {
originalThen && originalThen();
};
const sendRequest = (): Promise<Response> => {
return fetch(this.url, this.options).then((response) => {
if (response.ok) {
return response;
} else {
retries++;
if (retries <= times) {
return sendRequest();
} else {
throw new Error("Request failed after retries");
}
}
});
};
return sendRequest();
}
then(callback: (response: Response) => Promise<any>) {
return callback(new Response(""));
}
}
const client = (url: string, abort?: () => void) => {
return new Request(url, { abort });
};
export function useClient(url: string, options: RequestOptions) {
const [response, setResponse] = useState<Response | null>(null);
useEffect(() => {
const request = new Request(url, options);
request
.then((response) => response.json())
.then((data) => setResponse(data))
.catch((error) => console.error(error));
return () => {
request.options.abort && request.options.abort();
};
}, [url, options]);
return response;
}
Вы можете использовать этот хук в своих компонентах следующим образом:
import { useClient } from "./client";
function MyComponent() {
const response = useClient("https://...", {
headers: { Authorization: "..." },
abort: () => setTimeout(() => console.log("Aborted"), 2000),
});
if (response !== null) {
// Обрабатываем данные
return <div>{response}</div>;
}
return <div>Loading...</div>;
}
export default MyComponent;
При вызове хука useClient, будет происходить GET-запрос по указанному URL с заданными параметрами. Вы можете передать различные дополнительные параметры, такие как заголовки запроса или функцию прерывания (abort), которая будет вызвана через 2 секунды. Когда запрос будет выполнен и вернется ответ, его можно обработать в компоненте MyComponent. Если нет ошибок и ответ успешно получен, данные будут отображены. В противном случае будет выведено сообщение "Loading...".