Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

refactor(nuxt): enhance useFetch and useLazyFetch request type #4825

Merged
merged 28 commits into from
Jul 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
645bf0f
feat(nuxt): enchance `useFetch` and `useLazyFetch` request type #4823
didavid61202 May 5, 2022
c5579db
test(nuxt): add type tests for request param of `useFetch` and `useLa…
didavid61202 May 5, 2022
1e75775
docs(nuxt): update `useFetch` and `useLazyFetch` docs for request url…
didavid61202 May 5, 2022
a89ea15
test(nuxt): remove extra type test case for useFetch
didavid61202 May 5, 2022
863a512
docs(nuxt): update data-fetching and `useLazyFetch` docs
didavid61202 May 5, 2022
0cf1647
Merge branch 'main' into usefetch-request-url-type
didavid61202 May 6, 2022
3359b3b
fix(nuxt): configure vite to transpile nuxt (#4915)
danielroe May 10, 2022
61c280b
Merge commit '3359b3bc8e911d20b2e59ea39eace0cb815cb56e' into usefetch…
didavid61202 May 10, 2022
4db5e51
chore(nuxt):
didavid61202 May 10, 2022
a1477d5
refactor(nuxt): import request type `NitroFetchRequest` fron nitro b…
didavid61202 May 10, 2022
5a265e9
docs: update doc
didavid61202 May 10, 2022
b3c6d26
Revert "fix(nuxt): configure vite to transpile nuxt (#4915)"
didavid61202 May 10, 2022
fab4c2b
Update docs/content/3.api/1.composables/use-fetch.md
didavid61202 May 11, 2022
304da8b
Update docs/content/3.api/1.composables/use-fetch.md
didavid61202 May 11, 2022
89d2703
Update docs/content/2.guide/2.features/5.data-fetching.md
didavid61202 May 11, 2022
b7d8ce4
Update docs/content/3.api/1.composables/use-lazy-fetch.md
didavid61202 May 11, 2022
0baecd9
Update docs/content/2.guide/2.features/5.data-fetching.md
didavid61202 May 11, 2022
87e63e3
Merge commit 'cad4edd5a396c447ad99f4016bc856e197c9d85b' into usefetch…
didavid61202 May 12, 2022
3240ecf
chore: bump nitropack to 0.4.4
didavid61202 May 12, 2022
96fc3e3
fix: update `fetch.ts`
didavid61202 May 12, 2022
68fdbbb
test: update types test
didavid61202 May 12, 2022
b49385c
refactor: alias NitroFetchRequest and exclude `/_*` `/api/_*` interal…
didavid61202 May 12, 2022
8ca15f5
test: update types test
didavid61202 May 12, 2022
ccb661b
refactor: revert walkaround changes in types test
didavid61202 May 12, 2022
9a31608
fix last commit on types test
didavid61202 May 12, 2022
3ad6c2c
remove walkarounds
didavid61202 May 12, 2022
8ea23a3
docs: tweaks
danielroe May 12, 2022
25726e1
Merge remote-tracking branch 'origin/main' into usefetch-request-url-…
danielroe Jul 22, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content/2.guide/2.features/5.data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Nuxt provides `useFetch`, `useLazyFetch`, `useAsyncData` and `useLazyAsyncData`

Within your pages, components and plugins you can use `useFetch` to universally fetch from any URL.

This composable provides a convenient wrapper around `useAsyncData` and `$fetch`. It automatically generates a key based on URL and fetch options, as well as infers API response type.
This composable provides a convenient wrapper around `useAsyncData` and `$fetch`. It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.

::ReadMore{link="/api/composables/use-fetch"}
::
Expand Down
2 changes: 1 addition & 1 deletion docs/content/3.api/1.composables/use-fetch.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# `useFetch`

This composable provides a convenient wrapper around [`useAsyncData`](/api/composables/use-async-data) and [`$fetch`](/api/utils/$fetch). It automatically generates a key based on URL and fetch options, as well as infers API response type.
This composable provides a convenient wrapper around [`useAsyncData`](/api/composables/use-async-data) and [`$fetch`](/api/utils/$fetch). It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.

## Type

Expand Down
8 changes: 4 additions & 4 deletions packages/nuxt/src/app/composables/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { FetchOptions } from 'ohmyfetch'
import type { TypedInternalResponse, NitroFetchRequest } from 'nitropack'
import { computed, isRef, Ref } from 'vue'
import type { AsyncDataOptions, _Transform, KeyOfRes, AsyncData, PickFrom } from './asyncData'
Expand Down Expand Up @@ -48,11 +48,11 @@ export function useFetch<
const key = '$f' + _key

const _request = computed(() => {
let r = request as Ref<FetchRequest> | FetchRequest | (() => FetchRequest)
let r = request
if (typeof r === 'function') {
r = r()
}
return (isRef(r) ? r.value : r) as NitroFetchRequest
return (isRef(r) ? r.value : r)
})

const {
Expand Down Expand Up @@ -85,7 +85,7 @@ export function useFetch<
}

const asyncData = useAsyncData<_ResT, ErrorT, Transform, PickKeys>(key, () => {
return $fetch(_request.value, _fetchOptions)
return $fetch(_request.value, _fetchOptions) as Promise<_ResT>
}, _asyncDataOptions)

return asyncData
Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/core/runtime/nitro/error.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { withQuery } from 'ufo'
import type { NitroErrorHandler, NitroFetchRequest } from 'nitropack'
import type { NitroErrorHandler } from 'nitropack'
// @ts-ignore TODO
import { normalizeError, isJsonRequest } from '#internal/nitro/utils'

Expand Down Expand Up @@ -36,7 +36,7 @@ export default <NitroErrorHandler> async function errorhandler (_error, event) {
}

// HTML response
const url = withQuery('/__nuxt_error', errorObject as any) as NitroFetchRequest
const url = withQuery('/__nuxt_error', errorObject as any)
const html = await $fetch(url).catch((error) => {
console.error('[nitro] Error while generating error response', error)
return errorObject.statusMessage
Expand Down
14 changes: 14 additions & 0 deletions test/fixtures/basic/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,20 @@ describe('composables', () => {
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toMatchTypeOf<Ref<number>>()
})

it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl:string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toMatchTypeOf<Ref<Pick<unknown, never>>>()

// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()

// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toMatchTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toMatchTypeOf<Ref<Pick<unknown, never>>>()
})

it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toMatchTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toMatchTypeOf(useState(() => ({ foo: Math.random() })))
Expand Down