Skip to content

Commit

Permalink
fix: allow pathParams to be reactive getter (#39)
Browse files Browse the repository at this point in the history
* fix: allow pathParams to be a object ref

* refactor: use reactive getter for `pathParams`

---------

Co-authored-by: Johann Schopplich <[email protected]>
  • Loading branch information
mattmess1221 and johannschopplich authored Aug 26, 2023
1 parent e5537f7 commit 41bd30e
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 8 deletions.
12 changes: 12 additions & 0 deletions docs/guide/openapi-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**.
:::
Expand Down
8 changes: 4 additions & 4 deletions playground/pages/petStore.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ async function updateUser() {
})
await execute()
}
catch (e) {
console.error(e)
catch (error) {
console.error(error)
}
}
Expand All @@ -50,8 +50,8 @@ async function fetchPetData(petId: number) {
},
})
}
catch (e) {
console.error(e)
catch (error) {
console.error(error)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/composables/useApiData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export type UseApiDataOptions<T> = Pick<
| 'retryDelay'
| 'timeout'
> & {
pathParams?: MaybeRef<Record<string, string>>
pathParams?: MaybeRefOrGetter<Record<string, string>>
body?: MaybeRef<string | Record<string, any> | FormData | null | undefined>
} & BaseUseApiDataOptions<T>

Expand Down
5 changes: 2 additions & 3 deletions src/runtime/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,11 @@ export async function deserializeMaybeEncodedBody(value: ApiFetchOptions['body']
return value
}

export function resolvePath(path: string, params?: Record<string, string>) {
export function resolvePath(path: string, params?: Record<string, unknown>) {
// 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,
)
}
Expand Down

0 comments on commit 41bd30e

Please sign in to comment.