mirror of
https://github.com/checktheroads/hyperglass
synced 2024-05-11 05:55:08 +00:00
move fetchWithTimeout to ~/util for re-use [skip ci]
This commit is contained in:
@@ -1,36 +1,10 @@
|
||||
import { useQuery } from 'react-query';
|
||||
import { useConfig } from '~/context';
|
||||
import { fetchWithTimeout } from '~/util';
|
||||
|
||||
import type { TFormQuery } from '~/types';
|
||||
import type { TUseLGQueryFn } from './types';
|
||||
|
||||
/**
|
||||
* Fetch Wrapper that incorporates a timeout via a passed AbortController instance.
|
||||
*
|
||||
* Adapted from: https://lowmess.com/blog/fetch-with-timeout
|
||||
*/
|
||||
export async function fetchWithTimeout(
|
||||
uri: string,
|
||||
options: RequestInit = {},
|
||||
timeout: number,
|
||||
controller: AbortController,
|
||||
): Promise<Response> {
|
||||
/**
|
||||
* Lets set up our `AbortController`, and create a request options object that includes the
|
||||
* controller's `signal` to pass to `fetch`.
|
||||
*/
|
||||
const { signal = new AbortController().signal, ...allOptions } = options;
|
||||
const config = { ...allOptions, signal };
|
||||
/**
|
||||
* Set a timeout limit for the request using `setTimeout`. If the body of this timeout is
|
||||
* reached before the request is completed, it will be cancelled.
|
||||
*/
|
||||
setTimeout(() => {
|
||||
controller.abort();
|
||||
}, timeout);
|
||||
return await fetch(uri, config);
|
||||
}
|
||||
|
||||
export function useLGQuery(query: TFormQuery) {
|
||||
const { request_timeout, cache } = useConfig();
|
||||
const controller = new AbortController();
|
||||
|
Reference in New Issue
Block a user