Skip to content

Commit

Permalink
feat: allow for custom response parser with parseResponse (#16)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <[email protected]>
  • Loading branch information
chrstnfrrs and pi0 authored Oct 22, 2021
1 parent b5c0c3b commit 463ced6
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
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

0 comments on commit 463ced6

Please sign in to comment.