From 92ef27fd7c28b9b9aade02f4ec09b6132e9eb82a Mon Sep 17 00:00:00 2001 From: Johann Schopplich Date: Sat, 6 May 2023 08:07:36 +0200 Subject: [PATCH] feat: support reactive `body` (closes #20) --- src/runtime/composables/useApiData.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/runtime/composables/useApiData.ts b/src/runtime/composables/useApiData.ts index 1a2f551..df13490 100644 --- a/src/runtime/composables/useApiData.ts +++ b/src/runtime/composables/useApiData.ts @@ -1,8 +1,7 @@ -import { computed, reactive, unref } from 'vue' +import { computed, reactive } from 'vue' import { hash } from 'ohash' import type { FetchError } from 'ofetch' import type { NitroFetchOptions } from 'nitropack' -import type { Ref } from 'vue' import type { AsyncData, AsyncDataOptions } from 'nuxt/app' import type { ModuleOptions } from '../../module' import { headersToObject, serializeMaybeEncodedBody, toValue } from '../utils' @@ -14,8 +13,8 @@ type ComputedOptions> = { [K in keyof T]: T[K] extends Function ? T[K] : T[K] extends Record - ? ComputedOptions | Ref | T[K] - : Ref | T[K]; + ? ComputedOptions | MaybeRef + : MaybeRef; } export type UseApiDataOptions = AsyncDataOptions & Pick< @@ -28,7 +27,7 @@ export type UseApiDataOptions = AsyncDataOptions & Pick< | 'headers' | 'method' > & { - body?: string | Record | FormData | null + body?: MaybeRef | FormData | null | undefined> /** * Skip the Nuxt server proxy and fetch directly from the API. * Requires `allowClient` to be enabled in the module options as well. @@ -82,8 +81,9 @@ export function _useApiData( const _endpointFetchOptions: EndpointFetchOptions = reactive({ path: _path, query, - headers: computed(() => headersToObject(unref(headers as MaybeRef))), + headers: computed(() => headersToObject(toValue(headers))), method, + body, }) const _asyncDataOptions: AsyncDataOptions = { @@ -103,9 +103,9 @@ export function _useApiData( const key = computed(() => `$party${hash([ endpointId, _path.value, - unref(query), - unref(method), - ...(isFormData(body) ? [] : [body]), + toValue(query), + toValue(method), + ...(isFormData(toValue(body)) ? [] : [toValue(body)]), ])}`) return useAsyncData( @@ -138,7 +138,7 @@ export function _useApiData( ...endpoint.headers, ..._endpointFetchOptions.headers, }, - body, + body: _endpointFetchOptions.body, })) as T } else { @@ -150,7 +150,7 @@ export function _useApiData( method: 'POST', body: { ..._endpointFetchOptions, - body: await serializeMaybeEncodedBody(body), + body: await serializeMaybeEncodedBody(_endpointFetchOptions.body), } satisfies EndpointFetchOptions, }, )) as T