Skip to content

Commit

Permalink
feat: redirect interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
metcoder95 committed Mar 3, 2024
1 parent 8ac252d commit 8c8c064
Show file tree
Hide file tree
Showing 2 changed files with 685 additions and 36 deletions.
49 changes: 13 additions & 36 deletions lib/interceptor/redirect.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,21 @@
'use strict'

const { InvalidArgumentError } = require('../core/errors')
const Dispatcher = require('../dispatcher/dispatcher')
const RedirectHandler = require('../handler/redirect-handler')

class RedirectDispatcher extends Dispatcher {
#opts
#dispatcher

constructor (dispatcher, opts) {
super()

this.#dispatcher = dispatcher
this.#opts = opts
}

dispatch (opts, handler) {
return this.#dispatcher.dispatch(
opts,
new RedirectHandler(this.#dispatcher, opts, this.#opts, handler)
)
}

close (...args) {
return this.#dispatcher.close(...args)
}
module.exports = opts => {
const globalMaxRedirections = opts?.maxRedirections
return dispatcher => {
const dispatch = dispatcher.dispatch.bind(dispatcher)

destroy (...args) {
return this.#dispatcher.destroy(...args)
}
}
return function redirectInterceptor (opts, handler) {
const { maxRedirections = globalMaxRedirections } = opts

module.exports = opts => {
if (opts?.maxRedirections == null || opts?.maxRedirections === 0) {
return null
}
if (!maxRedirections) {
return dispatch(opts, handler)
}

if (!Number.isInteger(opts.maxRedirections) || opts.maxRedirections < 0) {
throw new InvalidArgumentError('maxRedirections must be a positive number')
const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
return dispatch(opts, redirectHandler)
}
}

return dispatcher => new RedirectDispatcher(dispatcher, opts)
}
Loading

0 comments on commit 8c8c064

Please sign in to comment.