fix(nuxt): correct return type of useRequestFetch (#30117)

This commit is contained in:
Daniel Roe 2024-12-02 15:40:44 +00:00
parent 9d78d7b062
commit a77c8f2e77
No known key found for this signature in database
GPG Key ID: 3714AB03996F442B
2 changed files with 20 additions and 2 deletions

View File

@ -2,6 +2,7 @@ import type { H3Event } from 'h3'
import { setResponseStatus as _setResponseStatus, appendHeader, getRequestHeader, getRequestHeaders, getResponseHeader, removeResponseHeader, setResponseHeader } from 'h3'
import { computed, getCurrentInstance, ref } from 'vue'
import { useServerHead } from '@unhead/vue'
import type { H3Event$Fetch } from 'nitro/types'
import type { NuxtApp } from '../nuxt'
import { useNuxtApp } from '../nuxt'
@ -39,11 +40,11 @@ export function useRequestHeader (header: string) {
}
/** @since 3.2.0 */
export function useRequestFetch (): typeof global.$fetch {
export function useRequestFetch (): H3Event$Fetch | typeof global.$fetch {
if (import.meta.client) {
return globalThis.$fetch
}
return useRequestEvent()?.$fetch as typeof globalThis.$fetch || globalThis.$fetch
return useRequestEvent()?.$fetch || globalThis.$fetch
}
/** @since 3.0.0 */

View File

@ -34,6 +34,23 @@ describe('API routes', () => {
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useRequestFetch', () => {
const $fetch = useRequestFetch()
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
// registered in extends
expectTypeOf($fetch('/api/foo')).toEqualTypeOf<Promise<string>>()
// registered in module
expectTypeOf($fetch('/auto-registered-module')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/hey', { method: 'get' })).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/hey', { method: 'post' })).toEqualTypeOf<Promise<{ method: 'post' }>>()
// @ts-expect-error not a valid method
expectTypeOf($fetch('/api/hey', { method: 'patch ' })).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/union')).toEqualTypeOf<Promise<{ type: 'a', foo: string } | { type: 'b', baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string | DefaultAsyncDataValue>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string } | DefaultAsyncDataValue>>()