Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
molvqingtai committed Dec 29, 2023
2 parents 49f2d6e + 537eee6 commit 6db0ce8
Show file tree
Hide file tree
Showing 23 changed files with 420 additions and 372 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,8 @@ console.log(await res.json()) // { foo: 'bar' }

> **Warning**
> Req & Res extends from [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) and [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response); to create a new request and response in the middleware, use `new Req()` and `new Res()`.
>
> To access the contents of the `body` in the current middleware, please use `Res.clone()` to ensure that the res received by the next middleware are unlocked.
### Interfaces

Expand Down
67 changes: 67 additions & 0 deletions __tests__/middlewares.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,4 +382,71 @@ describe('Test overload options', () => {

server.close()
})

test('Request retry', async () => {
const server = new Server()
const { origin: baseURL } = await server.listen()
const resreq = new Resreq({ baseURL, responseType: 'text' })

server.post('/api', async (ctx) => {
ctx.body = {
code: 401
}
})

server.post('/retry', async (ctx) => {
ctx.body = ctx.request.body
})

resreq.use((next) => async (req) => {
const body = req.clone().body
const res = await next(req)
const { code }: { code: number } = await res.json()
if (code === 401) {
const _resreq = new Resreq({ baseURL })
const _res = await _resreq.post('/retry', {
body: body!,
headers: {
'Content-Type': req.headers.get('Content-Type')!
}
})
return _res
} else {
return res
}
})

const res: string = await resreq.post('/api', {
body: 'foobar'
})
expect(res).toBe('foobar')

server.close()
})

test('Cancel request', async () => {
const server = new Server()
const { origin: baseURL } = await server.listen()
const resreq = new Resreq({ baseURL })

server.get('/api', async (ctx) => {
ctx.status = 200
})

const abortController = new AbortController()

resreq.use((next) => async (req) => {
abortController.abort()
return await next(req)
})

const res = resreq.request({
url: '/api',
signal: abortController.signal
})

await expect(res).rejects.toThrowError(/abort/)

server.close()
})
})
2 changes: 1 addition & 1 deletion docs/assets/search.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 6db0ce8

Please sign in to comment.