Skip to content

Commit

Permalink
refactor: add query alias to params option (#105)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
huynl-96 and pi0 committed Sep 19, 2022
1 parent c1f8d0f commit 363339d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,18 +125,18 @@ const article = await $fetch<Article>(`/api/article/${id}`)

## 鉁旓笍 Adding `baseURL`

By using `baseURL` option, `$fetch` prepends it with respecting to trailing/leading slashes and query params for baseURL using [ufo](https://github.com/unjs/ufo):
By using `baseURL` option, `$fetch` prepends it with respecting to trailing/leading slashes and query search params for baseURL using [ufo](https://github.com/unjs/ufo):

```js
await $fetch('/config', { baseURL })
```

## 鉁旓笍 Adding params
## 鉁旓笍 Adding Query Search Params

By using `params` option, `$fetch` adds params to URL by preserving params in request itself using [ufo](https://github.com/unjs/ufo):
By using `query` option (or `params` as alias), `$fetch` adds query search params to URL by preserving query in request itself using [ufo](https://github.com/unjs/ufo):

```js
await $fetch('/movie?lang=en', { params: { id: 123 } })
await $fetch('/movie?lang=en', { query: { id: 123 } })
```

## 鉁旓笍 Interceptors
Expand All @@ -155,9 +155,9 @@ await $fetch('/api', {
// Log request
console.log('[fetch request]', request, options)

// Add `?t=1640125211170` to query params
options.params = options.params
options.params.t = new Date()
// Add `?t=1640125211170` to query search params
options.query = options.query
options.query.t = new Date()
}
})
```
Expand Down
5 changes: 3 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface FetchOptions<R extends ResponseType = ResponseType> extends Omi
baseURL?: string
body?: RequestInit['body'] | Record<string, any>
params?: SearchParams
query?: SearchParams
parseResponse?: (responseText: string) => any
responseType?: R
response?: boolean
Expand Down Expand Up @@ -105,8 +106,8 @@ export function createFetch (globalOptions: CreateFetchOptions): $Fetch {
if (ctx.options.baseURL) {
ctx.request = withBase(ctx.request, ctx.options.baseURL)
}
if (ctx.options.params) {
ctx.request = withQuery(ctx.request, ctx.options.params)
if (ctx.options.query || ctx.options.params) {
ctx.request = withQuery(ctx.request, { ...ctx.options.params, ...ctx.options.query })
}
if (ctx.options.body && isPayloadMethod(ctx.options.method)) {
if (isJSONSerializable(ctx.options.body)) {
Expand Down

0 comments on commit 363339d

Please sign in to comment.