Skip to content

Commit

Permalink
feat!(nuxt): add dynamic Ref unwrapping to useRequest function
Browse files Browse the repository at this point in the history
This commit introduces the ability to handle dynamic `Ref` unwrapping in the `useRequest` function within the Nuxt package. The update includes modifications to both types and the request function, ensuring that `Ref` values are correctly unwrapped before being passed to the `request` method. This breaking change is crucial for supporting reactive programming patterns and enhancing the flexibility of the `useRequest` function.
  • Loading branch information
shorwood committed Sep 11, 2024
1 parent 706a1c3 commit 29ea54f
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions packages/nuxt/useRequest.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { InferOutput, InferRouteName, RequestOptions } from '@unserved/client'
import type { InferOutput, InferRouteName, RequestOptions, RequestOptionsData } from '@unserved/client'
import type { GlobalApplication } from '@unserved/nuxt/types'
import type { ApplicationOrModule } from '@unserved/server'
import type { AsyncDataOptions } from 'nuxt/app'
import type { MaybeRef } from 'vue'
import { useAsyncData } from 'nuxt/app'
import { unref } from 'vue'
import { useClient } from './useClient'

/** Extract the keys of an object but only if they are strings. */
Expand All @@ -11,6 +13,11 @@ export type KeysOf<T> = Array<T extends T
: never : never
>

/** Wrap an object as to allow for `Ref` values to be passed. */
export type MaybeRefWrap<T extends object> = MaybeRef<{
[K in keyof T]: MaybeRef<T[K]>
}>

/**
* The options to pass to the `useRequest` function. It extends the `AsyncDataOptions` and `RequestOptions` types
* with the `data` and `key` properties. The `data` property is the data to pass to the request, and the `key` property
Expand All @@ -31,7 +38,11 @@ export type UseRequestOptions<
U = O,
K extends KeysOf<U> = KeysOf<U>,
D = null,
> = { key?: string } & AsyncDataOptions<O, U, K, D> & RequestOptions<T, P>
> =
{ data?: MaybeRefWrap<RequestOptionsData<T, P>> } &
{ key?: string } &
AsyncDataOptions<O, U, K, D> &
Omit<RequestOptions<T, P>, 'data'>

export type UseRequestReturn<
T extends ApplicationOrModule,
Expand Down Expand Up @@ -71,7 +82,11 @@ export function useRequest<
): UseRequestReturn<T, P, O, U, K, D> {
return useAsyncData(
options.key ?? name as string,
() => useClient<T>().request(name, options),
() => {
const data = unref({ ...options.data }) as RequestOptionsData<T, P>
for (const key in data) data[key] = unref(data[key])
return useClient<T>().request(name, { ...options, data })
},
options,
)
}

0 comments on commit 29ea54f

Please sign in to comment.