Skip to content

Commit 8c8c064

Browse files
committed
feat: redirect interceptor
1 parent 8ac252d commit 8c8c064

File tree

2 files changed

+685
-36
lines changed

2 files changed

+685
-36
lines changed

lib/interceptor/redirect.js

+13-36
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,21 @@
11
'use strict'
2-
3-
const { InvalidArgumentError } = require('../core/errors')
4-
const Dispatcher = require('../dispatcher/dispatcher')
52
const RedirectHandler = require('../handler/redirect-handler')
63

7-
class RedirectDispatcher extends Dispatcher {
8-
#opts
9-
#dispatcher
10-
11-
constructor (dispatcher, opts) {
12-
super()
13-
14-
this.#dispatcher = dispatcher
15-
this.#opts = opts
16-
}
17-
18-
dispatch (opts, handler) {
19-
return this.#dispatcher.dispatch(
20-
opts,
21-
new RedirectHandler(this.#dispatcher, opts, this.#opts, handler)
22-
)
23-
}
24-
25-
close (...args) {
26-
return this.#dispatcher.close(...args)
27-
}
4+
module.exports = opts => {
5+
const globalMaxRedirections = opts?.maxRedirections
6+
return dispatcher => {
7+
const dispatch = dispatcher.dispatch.bind(dispatcher)
288

29-
destroy (...args) {
30-
return this.#dispatcher.destroy(...args)
31-
}
32-
}
9+
return function redirectInterceptor (opts, handler) {
10+
const { maxRedirections = globalMaxRedirections } = opts
3311

34-
module.exports = opts => {
35-
if (opts?.maxRedirections == null || opts?.maxRedirections === 0) {
36-
return null
37-
}
12+
if (!maxRedirections) {
13+
return dispatch(opts, handler)
14+
}
3815

39-
if (!Number.isInteger(opts.maxRedirections) || opts.maxRedirections < 0) {
40-
throw new InvalidArgumentError('maxRedirections must be a positive number')
16+
const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
17+
opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
18+
return dispatch(opts, redirectHandler)
19+
}
4120
}
42-
43-
return dispatcher => new RedirectDispatcher(dispatcher, opts)
4421
}

0 commit comments

Comments
 (0)