Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow for custom response parser with parseResponse #16

Merged
merged 12 commits into from
Oct 22, 2021
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ We use [conditional exports](https://nodejs.org/api/packages.html#packages_condi
const { users } = await $fetch('/api/users')
```

You can optionally provde a different parser than destr.

```js
// Use JSON.parse
await $fetch('/movie?lang=en', { parseResponse: JSON.parse })

// Return text as is
await $fetch('/movie?lang=en', { parseResponse: txt => txt })
```

## ✔️ JSON Body

`$fetch` automatically stringifies request body (if an object is passed) and adds JSON `Content-Type` headers (for `put`, `patch` and `post` requests).
Expand Down
8 changes: 5 additions & 3 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface FetchOptions extends Omit<RequestInit, 'body'> {
baseURL?: string
body?: RequestInit['body'] | Record<string, any>
params?: SearchParams
parseResponse?: (responseText: string) => any
response?: boolean
}

Expand Down Expand Up @@ -44,8 +45,8 @@ export function setHeader (options: FetchOptions, _key: string, value: string) {
}

export function createFetch ({ fetch }: CreateFetchOptions): $Fetch {
const raw: $Fetch['raw'] = async function (request, opts) {
if (opts && typeof request === 'string') {
const raw: $Fetch['raw'] = async function (request, opts = {}) {
if (typeof request === 'string') {
if (opts.baseURL) {
request = joinURL(opts.baseURL, request)
}
Expand All @@ -59,7 +60,8 @@ export function createFetch ({ fetch }: CreateFetchOptions): $Fetch {
}
const response: FetchResponse<any> = await fetch(request, opts as RequestInit)
const text = await response.text()
response.data = destr(text)
const parseFn = opts.parseResponse || destr
response.data = parseFn(text)
if (!response.ok) {
throw createFetchError(request, response)
}
Expand Down
8 changes: 7 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe('ohmyfetch', () => {
let listener: Listener
const getURL = (url: string) => joinURL(listener.url, url)

it('setup', async () => {
beforeAll(async () => {
const app = createApp()
.use('/ok', () => 'ok')
.use('/params', req => (getQuery(req.url || '')))
Expand All @@ -25,6 +25,12 @@ describe('ohmyfetch', () => {
expect(await $fetch(getURL('ok'))).toBe('ok')
})

it('custom parseResponse', async () => {
const parser = jest.fn().mockReturnValue('asdf')
await $fetch(getURL('ok'), { parseResponse: parser })
expect(parser).toHaveBeenCalledTimes(1)
})

it('baseURL', async () => {
expect(await $fetch('/x?foo=123', { baseURL: getURL('url') })).toBe('/x?foo=123')
})
Expand Down