|
| 1 | +import { |
| 2 | + type CreateFetchOptions, |
| 3 | + type UseFetchOptions, |
| 4 | + type UseFetchReturn, |
| 5 | + createFetch, |
| 6 | +} from '@vueuse/core' |
| 7 | +import { type MaybeRefOrGetter, toValue } from 'vue' |
| 8 | +import { |
| 9 | + type FetchResponseData, |
| 10 | + type FilterMethods, |
| 11 | + type ParamsOption, |
| 12 | + type RequestBodyOption, |
| 13 | + createOpenFetch, |
| 14 | +} from '#/utils/fetch' |
| 15 | + |
| 16 | +type MethodOption<M, P> = 'get' extends keyof P ? { method?: M } : { method: M } |
| 17 | + |
| 18 | +type UseOpenFetchOptions< |
| 19 | + Method, |
| 20 | + LowercasedMethod, |
| 21 | + Params, |
| 22 | + Operation = 'get' extends LowercasedMethod |
| 23 | + ? 'get' extends keyof Params |
| 24 | + ? Params['get'] |
| 25 | + : never |
| 26 | + : LowercasedMethod extends keyof Params |
| 27 | + ? Params[LowercasedMethod] |
| 28 | + : never, |
| 29 | +> = MethodOption<Method, Params> & |
| 30 | + ParamsOption<Operation> & |
| 31 | + RequestBodyOption<Operation> |
| 32 | + |
| 33 | +export type UseOpenFetchClient<Paths> = < |
| 34 | + Path extends Extract<keyof Paths, string>, |
| 35 | + Methods extends FilterMethods<Paths[Path]>, |
| 36 | + Method extends |
| 37 | + | Extract<keyof Methods, string> |
| 38 | + | Uppercase<Extract<keyof Methods, string>>, |
| 39 | + LowercasedMethod extends Lowercase<Method> extends keyof Methods |
| 40 | + ? Lowercase<Method> |
| 41 | + : never, |
| 42 | + DefaultMethod extends 'get' extends LowercasedMethod |
| 43 | + ? 'get' |
| 44 | + : LowercasedMethod, |
| 45 | + ResT = FetchResponseData<Methods[DefaultMethod]>, |
| 46 | +>( |
| 47 | + path: Path | (() => Path), |
| 48 | + options: UseOpenFetchOptions<Method, LowercasedMethod, Methods>, |
| 49 | + useFetchOptions?: UseFetchOptions, |
| 50 | +) => UseFetchReturn<ResT> & PromiseLike<UseFetchReturn<ResT>> |
| 51 | + |
| 52 | +export function createUseOpenFetch<Paths>( |
| 53 | + config: CreateFetchOptions, |
| 54 | +): UseOpenFetchClient<Paths> { |
| 55 | + const useFetch = createFetch({ |
| 56 | + ...config, |
| 57 | + options: { |
| 58 | + fetch: createOpenFetch({ |
| 59 | + baseURL: toValue(config.baseUrl), |
| 60 | + }), |
| 61 | + }, |
| 62 | + }) |
| 63 | + |
| 64 | + return ( |
| 65 | + url: MaybeRefOrGetter<string>, |
| 66 | + requests: any, //TODO: find a way to type this |
| 67 | + useFetchOptions?: UseFetchOptions, |
| 68 | + ) => { |
| 69 | + return useFetch(toValue(url), requests, useFetchOptions) |
| 70 | + } |
| 71 | +} |
0 commit comments