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: Add onSuccess and onError interceptors #340

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,31 @@ import { defaults } from 'mande'
defaults.headers.Authorization = 'Bearer token'
```

You can intercept successfull or errored responses before they are handled by then or catch

Globaly
```js
import { defaults } from 'mande'

defaults.onError = (error) => {
notify(`Error from API: ${error.message}`)
return error
}
```
Or in a single instance
```js
import { mande } from 'mande'

const todos = mande('/api/todos', {
onSuccess: (plainTodos) => plainTodos.map((plainTodo) => new Todo({
...plainTodo,
createdAt: new Date(plainTodo.timestamp),
}))
})
todos.get('/opened').then((todos) => { /* Do stuff with transformed todos */ })
todos.get('/finished').then((todos) => { /* Here too */ })
```

## TypeScript

All methods defined on a `mande` instance accept a type generic to type their return:
Expand Down
56 changes: 56 additions & 0 deletions __tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,4 +277,60 @@ describe('mande', () => {
await expect(api.get('/2')).resolves.toEqual({})
expect(fetchMock).toHaveFetched('/api/2')
})

it('call the onSuccess handler', async () => {
const handler = jest.fn((res): any => {
expect(res).toEqual({ foo: 'bar' })
return { foo: 'baz' }
})
fetchMock.mock('/api/2', { status: 200, body: { foo: 'bar' } })
let api = mande('/api', { onSuccess: handler })
await expect(api.get('/2')).resolves.toEqual({ foo: 'baz' })
expect(handler).toBeCalledTimes(1)
})

it('call the onError handler', async () => {
const handler = jest.fn((err): any => {
expect(err).toBeInstanceOf(Error)
expect(err).toMatchObject({
response: expect.anything(),
body: { foo: 'bar' },
})
err.body = { foo: 'baz' }
return err
})
fetchMock.mock('/api/2', { status: 500, body: { foo: 'bar' } })
let api = mande('/api', { onError: handler })
await expect(api.get('/2')).rejects.toMatchObject({
response: expect.anything(),
body: { foo: 'baz' },
})
expect(handler).toBeCalledTimes(1)
})

it('call the onSuccess handler from default options', async () => {
const handler = jest.fn(async (res): Promise<string> => {
expect(res).toEqual({ foo: 'bar' })
await Promise.resolve();
return 'Hello'
})
defaults.onSuccess = handler
fetchMock.mock('/api/2', { status: 200, body: { foo: 'bar' } })
let api = mande('/api')
await expect(api.get('/2')).resolves.toEqual('Hello')
expect(handler).toBeCalledTimes(1)
delete defaults.onSuccess
})

it('call the handler from instance options over default options', async () => {
const handlerDefault = jest.fn((res) => ({ bar: 'foo' }))
const handlerInstance = jest.fn(async (res) => Promise.resolve({ foo: 'baz' }))
defaults.onSuccess = handlerDefault
fetchMock.mock('/api/2', { status: 200, body: { foo: 'bar' } })
let api = mande('/api', { onSuccess: handlerInstance })
await expect(api.get('/2')).resolves.toMatchObject({ foo: 'baz' })
expect(handlerDefault).toBeCalledTimes(0)
expect(handlerInstance).toBeCalledTimes(1)
delete defaults.onSuccess
})
})
23 changes: 20 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,20 @@ export interface Options<ResponseAs extends ResponseAsTypes = ResponseAsTypes>
* Headers sent alongside the request
*/
headers?: Record<string, string>

/**
* Intercept the success response
* @param response The response that would naturaly be returned if not set
* @return transformed (or not) data
*/
onSuccess?(response: Response): Response | unknown | Promise<Response | unknown>

/**
* Intercept the error response
* @param error The error that would naturaly be thrown if not set
* @return transformed (or not) data
*/
onError?(error: MandeError): MandeError | unknown | Promise<MandeError | unknown>
}

export type ResponseAsTypes = 'json' | 'text' | 'response'
Expand Down Expand Up @@ -311,13 +325,16 @@ export function mande(
.then(([response, data]) => {
if (response.status >= 200 && response.status < 300) {
// data is a raw response when responseAs is response
return responseAs !== 'response' && response.status == 204
? null
: data
const resp =
responseAs !== 'response' && response.status == 204 ? null : data
if (mergedOptions.onSuccess) return mergedOptions.onSuccess(resp)
return resp
}
let err = new Error(response.statusText) as MandeError
err.response = response
err.body = data
if (mergedOptions.onError)
return Promise.reject(mergedOptions.onError(err))
throw err
})
}
Expand Down