import { HttpOperationResponse } from "../httpOperationResponse" ; import { URLBuilder } from "../url" ; import { WebResourceLike } from "../webResource" ; import { BaseRequestPolicy , RequestPolicy , RequestPolicyFactory , RequestPolicyOptionsLike , } from "./requestPolicy" ; /**
 * Options for how redirect responses are handled.
 */ export interface RedirectOptions { handleRedirects : boolean ; maxRetries ? : number ; } export const DefaultRedirectOptions = { handleRedirects : true , maxRetries : 20 , } ; export function redirectPolicy ( maximumRetries = 20 ) { return { create : ( nextPolicy , options ) => { return new RedirectPolicy ( nextPolicy , options , maximumRetries ) ; } , } ; } export class RedirectPolicy extends BaseRequestPolicy { constructor ( nextPolicy , options , readonly maxRetries = 20 ) { super ( nextPolicy , options ) ; } public sendRequest ( request ) { return this . _nextPolicy . sendRequest ( request ) . then ( ( response ) => handleRedirect ( this , response , 0 ) ) ; } } function handleRedirect ( policy , response , currentRetries ) { const { request , status } = response ; const locationHeader = response . headers . get ( "location" ) ; if ( locationHeader && ( status === 300 || ( status === 301 && [ "GET" , "HEAD" ] . includes ( request . method ) ) || ( status === 302 && [ "GET" , "POST" , "HEAD" ] . includes ( request . method ) ) || ( status === 303 && "POST" === request . method ) || status === 307 ) && ( ( request . redirectLimit !== undefined && currentRetries < request . redirectLimit ) || ( request . redirectLimit === undefined && currentRetries < policy . maxRetries ) ) ) { const builder = URLBuilder . parse ( request . url ) ; builder . setPath ( locationHeader ) ; request . url = builder . toString ( ) ; if ( ( status === 302 || status === 303 ) && request . method === "POST" ) { request . method = "GET" ; delete request . body ; } return policy . _nextPolicy . sendRequest ( request ) . then ( ( res ) => handleRedirect ( policy , res , currentRetries + 1 ) ) . then ( ( res ) => recordRedirect ( res , request . url ) ) ; } return Promise . resolve ( response ) ; } function recordRedirect ( response , redirect ) { if ( ! response . redirected ) { response . redirected = true ; response . url = redirect ; } return response ; }