Skip to content

Commit

Permalink
refactor(types): useFetch return type (vitest-dev#653)
Browse files Browse the repository at this point in the history
Co-authored-by: webfansplz <>
  • Loading branch information
webfansplz committed Aug 9, 2021
1 parent 8bc027c commit 867f830
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 31 deletions.
46 changes: 46 additions & 0 deletions packages/core/useFetch/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,50 @@ describe('useFetch', () => {
expect(didErrorEventFire).toBe(true)
expect(didFinallyEventFire).toBe(true)
})

test('setting the request method w/ get and return type w/ json', async() => {
fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 })

const { data, isFinished } = useFetch('https://example.com').get().json()

await until(isFinished).toBe(true)

expect(data.value).toStrictEqual({ message: 'Hello World' })
})

test('setting the request method w/ post and return type w/ text', async() => {
fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 })

const { data, isFinished } = useFetch('https://example.com').post().text()

await until(isFinished).toBe(true)

expect(data.value).toStrictEqual(JSON.stringify({ message: 'Hello World' }))
})

test('allow setting response type before doing request', async() => {
fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 })

const shell = useFetch('https://example.com', {
immediate: false,
}).get().text()
shell.json()
shell.execute()
const { isFinished, data } = shell
await until(isFinished).toBe(true)

expect(data.value).toStrictEqual({ message: 'Hello World' })
})

test('not allowed setting response type while doing request', async() => {
fetchMock.mockResponse(JSON.stringify({ message: 'Hello World' }), { status: 200 })

const shell = useFetch('https://example.com').get().text()
const { isFetching, isFinished, data } = shell
await until(isFetching).toBe(true)
shell.json()
await until(isFinished).toBe(true)

expect(data.value).toStrictEqual(JSON.stringify({ message: 'Hello World' }))
})
})
50 changes: 19 additions & 31 deletions packages/core/useFetch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Ref, ref, unref, watch, computed, ComputedRef, shallowRef } from 'vue-d
import { Fn, MaybeRef, containsProp, createEventHook, EventHookOn } from '@vueuse/shared'
import { defaultWindow } from '../_configurable'

interface UseFetchReturnBase<T> {
interface UseFetchReturn<T> {
/**
* Indicates if the fetch request has finished
*/
Expand Down Expand Up @@ -68,6 +68,19 @@ interface UseFetchReturnBase<T> {
* Fires after a fetch has completed
*/
onFetchFinally: EventHookOn

// methods
get(): UseFetchReturn<T>
post(payload?: unknown, type?: string): UseFetchReturn<T>
put(payload?: unknown, type?: string): UseFetchReturn<T>
delete(payload?: unknown, type?: string): UseFetchReturn<T>

// type
json<JSON = any>(): UseFetchReturn<JSON>
text(): UseFetchReturn<string>
blob(): UseFetchReturn<Blob>
arrayBuffer(): UseFetchReturn<ArrayBuffer>
formData(): UseFetchReturn<FormData>
}

type DataType = 'text' | 'json' | 'blob' | 'arrayBuffer' | 'formData'
Expand All @@ -79,23 +92,6 @@ const payloadMapping: Record<string, string> = {
formData: 'multipart/form-data',
}

interface UseFetchReturnTypeConfigured<T> extends UseFetchReturnBase<T> {
// methods
get(): UseFetchReturnBase<T>
post(payload?: unknown, type?: string): UseFetchReturnBase<T>
put(payload?: unknown, type?: string): UseFetchReturnBase<T>
delete(payload?: unknown, type?: string): UseFetchReturnBase<T>
}

export interface UseFetchReturn<T> extends UseFetchReturnTypeConfigured<T> {
// type
json<JSON = any>(): UseFetchReturnTypeConfigured<JSON>
text(): UseFetchReturnTypeConfigured<string>
blob(): UseFetchReturnTypeConfigured<Blob>
arrayBuffer(): UseFetchReturnTypeConfigured<ArrayBuffer>
formData(): UseFetchReturnTypeConfigured<FormData>
}

export interface BeforeFetchContext {
/**
* The computed url of the current request
Expand Down Expand Up @@ -377,7 +373,7 @@ export function useFetch<T>(url: MaybeRef<string>, ...args: any[]): UseFetchRetu
{ deep: true },
)

const base: UseFetchReturnBase<T> = {
const shell: UseFetchReturn<T> = {
isFinished,
statusCode,
response,
Expand All @@ -392,20 +388,12 @@ export function useFetch<T>(url: MaybeRef<string>, ...args: any[]): UseFetchRetu
onFetchResponse: responseEvent.on,
onFetchError: errorEvent.on,
onFetchFinally: finallyEvent.on,
}

const typeConfigured: UseFetchReturnTypeConfigured<T> = {
...base,

// method
get: setMethod('get'),
put: setMethod('put'),
post: setMethod('post'),
delete: setMethod('delete'),
}

const shell: UseFetchReturn<T> = {
...typeConfigured,

// type
json: setType('json'),
text: setType('text'),
blob: setType('blob'),
Expand All @@ -424,7 +412,7 @@ export function useFetch<T>(url: MaybeRef<string>, ...args: any[]): UseFetchRetu
if (!payloadType && payload && Object.getPrototypeOf(payload) === Object.prototype)
config.payloadType = 'json'

return base as any
return shell as any
}
return undefined
}
Expand All @@ -434,7 +422,7 @@ export function useFetch<T>(url: MaybeRef<string>, ...args: any[]): UseFetchRetu
return () => {
if (!isFetching.value) {
config.type = type
return typeConfigured as any
return shell as any
}
return undefined
}
Expand Down

0 comments on commit 867f830

Please sign in to comment.