forked from mirrors/thatmattlove-hyperglass
move fetchWithTimeout to ~/util for re-use [skip ci]
This commit is contained in:
parent
d0b78ae69f
commit
5aabbab4bb
2 changed files with 28 additions and 27 deletions
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -73,3 +73,30 @@ export function arrangeIntoTree<P extends any>(paths: P[][]): PathPart[] {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue