Skip to content

Commit 143f5b1

Browse files
committed
feat: custom open fetch by ofetch
1 parent dec3c7f commit 143f5b1

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/utils/__tests__/fetch.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { createOpenFetch } from '../fetch'
3+
import type { paths } from '#/generated/api-schema'
4+
5+
describe('fetch', () => {
6+
it('should fill path correctly', async () => {
7+
const $fetch = createOpenFetch<paths>({
8+
baseURL: 'https://api.example.com',
9+
})
10+
11+
await $fetch('/auth/login', {
12+
method: 'POST',
13+
body: {
14+
15+
password: 'password',
16+
},
17+
})
18+
19+
await $fetch('/pets/{id}', {})
20+
})
21+
})

src/utils/fetch.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,11 @@ export type OpenFetchClient<Paths> = <
7474
? 'get'
7575
: LowercasedMethod,
7676
ResT = FetchResponseData<Paths[ReqT][DefaultMethod]>,
77+
ErrorT = FetchResponseError<Methods[DefaultMethod]>,
7778
>(
7879
url: ReqT,
7980
options?: OpenFetchOptions<Method, LowercasedMethod, Methods>,
80-
) => Promise<ResT>
81+
) => Promise<ResT | ErrorT>
8182

8283
// More flexible way to rewrite the request path,
8384
// but has problems - https://github.com/unjs/ofetch/issues/319
@@ -91,7 +92,7 @@ export function openFetchRequestInterceptor(ctx: FetchContext) {
9192
export function createOpenFetch<Paths>(
9293
options: FetchOptions | ((options: FetchOptions) => FetchOptions),
9394
): OpenFetchClient<Paths> {
94-
return (url: string, opts: any) => {
95+
return (url: string, opts: any = {}) => {
9596
return $fetch(
9697
fillPath(url, opts?.path),
9798
typeof options === 'function'

0 commit comments

Comments
 (0)