-
-
Notifications
You must be signed in to change notification settings - Fork 527
/
Copy pathquery-base.ts
61 lines (55 loc) · 2.05 KB
/
query-base.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import type { Client } from "openapi-fetch";
import type { MediaType, PathsWithMethod, RequiredKeysOf } from "openapi-typescript-helpers";
import type { Fetcher, SWRHook } from "swr";
import type { TypesForGetRequest } from "./types.js";
import { useCallback, useDebugValue, useMemo } from "react";
export const RESPONSE = Symbol.for("response");
/**
* @private
*/
export function configureBaseQueryHook(useHook: SWRHook) {
return function createQueryBaseHook<Paths extends {}, IMediaType extends MediaType, Prefix extends string>(
client: Client<Paths, IMediaType>,
prefix: Prefix,
) {
return function useQuery<
Path extends PathsWithMethod<Paths, "get">,
R extends TypesForGetRequest<Paths, Path>,
Init extends R["Init"],
Data extends R["Data"],
Error extends R["Error"],
Config extends R["SWRConfig"],
>(
path: Path,
...[init, config]: RequiredKeysOf<Init> extends never ? [(Init | null)?, Config?] : [Init | null, Config?]
) {
useDebugValue(`${prefix} - ${path as string}`);
const key = useMemo(() => (init !== null ? ([prefix, path, init] as const) : null), [prefix, path, init]);
type Key = typeof key;
// TODO: Lift up fetcher to and remove useCallback
const fetcher: Fetcher<Data, Key> = useCallback(
async ([_, path, init]) => {
// @ts-expect-error TODO: Improve internal init types
const res = await client.GET(path, init);
if (res.error) {
Object.defineProperty(res.error, RESPONSE, {
value: res.response,
enumerable: false,
});
throw res.error;
}
if (res.data && typeof res.data === "object") {
Object.defineProperty(res.data, RESPONSE, {
value: res.response,
enumerable: false,
});
}
return res.data as Data;
},
[client],
);
// @ts-expect-error TODO: Improve internal config types
return useHook<Data, Error, Key>(key, fetcher, config);
};
};
}