From 41bd30e26c60954f9e844611e057dfa928926bc6 Mon Sep 17 00:00:00 2001 From: Matthew Messinger Date: Sat, 26 Aug 2023 06:17:14 -0400 Subject: [PATCH] fix: allow `pathParams` to be reactive getter (#39) * fix: allow pathParams to be a object ref * refactor: use reactive getter for `pathParams` --------- Co-authored-by: Johann Schopplich --- docs/guide/openapi-types.md | 12 ++++++++++++ playground/pages/petStore.vue | 8 ++++---- src/runtime/composables/useApiData.ts | 2 +- src/runtime/utils.ts | 5 ++--- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/docs/guide/openapi-types.md b/docs/guide/openapi-types.md index 7472961..a0b9a2b 100644 --- a/docs/guide/openapi-types.md +++ b/docs/guide/openapi-types.md @@ -145,6 +145,18 @@ const data = await $myApi('foo/{id}', { }) ``` +For reactive `pathParams`, pass a ref or getter function instead of a plain object. + +```ts +const id = ref(10) + +const data = await $myApi('foo/{id}', { + pathParams: () => ({ + id: id.value + }) +}) +``` + ::: warning Issues will **NOT** be reported at runtime by `nuxt-api-party` if the wrong parameters are used. The **incomplete** path will be sent to the backend **AS IS**. ::: diff --git a/playground/pages/petStore.vue b/playground/pages/petStore.vue index 0fa9a6e..ba86dab 100644 --- a/playground/pages/petStore.vue +++ b/playground/pages/petStore.vue @@ -25,8 +25,8 @@ async function updateUser() { }) await execute() } - catch (e) { - console.error(e) + catch (error) { + console.error(error) } } @@ -50,8 +50,8 @@ async function fetchPetData(petId: number) { }, }) } - catch (e) { - console.error(e) + catch (error) { + console.error(error) } } diff --git a/src/runtime/composables/useApiData.ts b/src/runtime/composables/useApiData.ts index a2898a5..59fe9f0 100644 --- a/src/runtime/composables/useApiData.ts +++ b/src/runtime/composables/useApiData.ts @@ -51,7 +51,7 @@ export type UseApiDataOptions = Pick< | 'retryDelay' | 'timeout' > & { - pathParams?: MaybeRef> + pathParams?: MaybeRefOrGetter> body?: MaybeRef | FormData | null | undefined> } & BaseUseApiDataOptions diff --git a/src/runtime/utils.ts b/src/runtime/utils.ts index 8a79114..f03399e 100644 --- a/src/runtime/utils.ts +++ b/src/runtime/utils.ts @@ -41,12 +41,11 @@ export async function deserializeMaybeEncodedBody(value: ApiFetchOptions['body'] return value } -export function resolvePath(path: string, params?: Record) { +export function resolvePath(path: string, params?: Record) { // To simplify typings, OpenAPI path parameters can be expanded here if (params) { return Object.entries(params).reduce( - (path, [name, value]) => - path.replace(`{${name}}`, encodeURIComponent(value)), + (path, [name, value]) => path.replace(`{${name}}`, encodeURIComponent(String(value))), path, ) }