2021-10-20 09:43:08 +00:00
|
|
|
import type { FetchOptions, FetchRequest } from 'ohmyfetch'
|
2021-10-22 22:33:22 +00:00
|
|
|
import type { TypedInternalResponse } from '@nuxt/nitro'
|
2021-10-18 18:31:18 +00:00
|
|
|
import { murmurHashV3 } from 'murmurhash-es'
|
2021-10-11 22:36:50 +00:00
|
|
|
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
|
|
|
|
import { useAsyncData } from './asyncData'
|
|
|
|
|
2021-10-22 22:33:22 +00:00
|
|
|
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
|
2021-10-11 22:36:50 +00:00
|
|
|
|
|
|
|
export type UseFetchOptions<
|
|
|
|
DataT,
|
|
|
|
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
|
|
|
|
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
|
|
|
|
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
|
|
|
|
|
|
|
|
export function useFetch<
|
2022-02-16 20:50:19 +00:00
|
|
|
ResT = void,
|
2021-11-15 12:09:07 +00:00
|
|
|
ReqT extends string = string,
|
2022-02-16 20:50:19 +00:00
|
|
|
_ResT = ResT extends void ? FetchResult<ReqT> : ResT,
|
|
|
|
Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,
|
2021-11-15 12:09:07 +00:00
|
|
|
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
|
|
|
|
> (
|
2021-10-11 22:36:50 +00:00
|
|
|
url: ReqT,
|
2022-02-16 20:50:19 +00:00
|
|
|
opts: UseFetchOptions<_ResT, Transform, PickKeys> = {}
|
2021-10-11 22:36:50 +00:00
|
|
|
) {
|
|
|
|
if (!opts.key) {
|
|
|
|
const keys: any = { u: url }
|
|
|
|
if (opts.baseURL) {
|
|
|
|
keys.b = opts.baseURL
|
|
|
|
}
|
|
|
|
if (opts.method && opts.method.toLowerCase() !== 'get') {
|
|
|
|
keys.m = opts.method.toLowerCase()
|
|
|
|
}
|
|
|
|
if (opts.params) {
|
|
|
|
keys.p = opts.params
|
|
|
|
}
|
|
|
|
opts.key = generateKey(keys)
|
|
|
|
}
|
|
|
|
|
2022-02-16 20:50:19 +00:00
|
|
|
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<_ResT>, opts)
|
2021-10-11 22:36:50 +00:00
|
|
|
}
|
|
|
|
|
2021-11-15 12:09:07 +00:00
|
|
|
export function useLazyFetch<
|
2022-02-16 20:50:19 +00:00
|
|
|
ResT = void,
|
2021-11-15 12:09:07 +00:00
|
|
|
ReqT extends string = string,
|
2022-02-16 20:50:19 +00:00
|
|
|
_ResT = ResT extends void ? FetchResult<ReqT> : ResT,
|
|
|
|
Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,
|
2021-11-15 12:09:07 +00:00
|
|
|
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
|
|
|
|
> (
|
|
|
|
url: ReqT,
|
2022-02-16 20:50:19 +00:00
|
|
|
opts: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'> = {}
|
2021-11-15 12:09:07 +00:00
|
|
|
) {
|
|
|
|
return useFetch(url, { ...opts, lazy: true })
|
|
|
|
}
|
|
|
|
|
2021-10-11 22:36:50 +00:00
|
|
|
function generateKey (keys) {
|
2021-10-18 18:31:18 +00:00
|
|
|
return '$f' + murmurHashV3(JSON.stringify(keys))
|
2021-10-11 22:36:50 +00:00
|
|
|
}
|