Skip to content

Commit a13b968

Browse files
SkyZeroZxthePunderWoman
authored andcommitted
fix(http): run root interceptors in the terminal request chain
Represent withRequestsMadeViaParent() with an internal delegating backend so the interceptor handler can distinguish delegated clients from independent child configurations. (cherry picked from commit bb78286)
1 parent 115abc2 commit a13b968

4 files changed

Lines changed: 313 additions & 13 deletions

File tree

‎packages/common/http/src/backend.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,15 @@ export class HttpInterceptorHandler implements HttpHandler {
9999

100100
handle(initialRequest: HttpRequest<any>): Observable<HttpEvent<any>> {
101101
if (this.chain === null) {
102+
const parentHandler = this.injector.get(HttpHandler, null, {skipSelf: true});
103+
const isDelegating = parentHandler !== null && this.backend === parentHandler;
104+
const rootInterceptorFns = this.injector.get(
105+
HTTP_ROOT_INTERCEPTOR_FNS,
106+
[],
107+
isDelegating ? {self: true} : undefined,
108+
);
102109
const dedupedInterceptorFns = Array.from(
103-
new Set([
104-
...this.injector.get(HTTP_INTERCEPTOR_FNS),
105-
...this.injector.get(HTTP_ROOT_INTERCEPTOR_FNS, []),
106-
]),
110+
new Set([...this.injector.get(HTTP_INTERCEPTOR_FNS), ...rootInterceptorFns]),
107111
);
108112

109113
// Note: interceptors are wrapped right-to-left so that final execution order is

‎packages/common/http/src/provider.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,15 @@ export function provideHttpClient(
106106
featureKinds.has(HttpFeatureKind.CustomXsrfConfiguration)
107107
) {
108108
throw new Error(
109-
ngDevMode
110-
? `Configuration error: found both withXsrfConfiguration() and withNoXsrfProtection() in the same call to provideHttpClient(), which is a contradiction.`
111-
: '',
109+
`Configuration error: found both withXsrfConfiguration() and withNoXsrfProtection() in the same call to provideHttpClient(), which is a contradiction.`,
110+
);
111+
}
112+
113+
const hasBackendOverride =
114+
featureKinds.has(HttpFeatureKind.Fetch) || featureKinds.has(HttpFeatureKind.Xhr);
115+
if (featureKinds.has(HttpFeatureKind.RequestsMadeViaParent) && hasBackendOverride) {
116+
throw new Error(
117+
`Configuration error: withRequestsMadeViaParent() cannot be combined with withFetch() or withXhr() in the same call to provideHttpClient().`,
112118
);
113119
}
114120
}
@@ -267,6 +273,9 @@ export function withJsonpSupport(): HttpFeature<HttpFeatureKind.JsonpSupport> {
267273
* "bubble up" until either reaching the root level or an `HttpClient` which was not configured with
268274
* this option.
269275
*
276+
* This feature cannot be combined with `withFetch` or `withXhr` in the same
277+
* `provideHttpClient()` call.
278+
*
270279
* @see [HTTP client setup](guide/http/setup#withrequestsmadeviaparent)
271280
* @see {@link provideHttpClient}
272281
* @publicApi 19.0

‎packages/common/http/test/provider_spec.ts‎

Lines changed: 171 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,14 @@ import {
3737
} from '@angular/core';
3838
import {TestBed} from '@angular/core/testing';
3939
import {EMPTY, Observable, from} from 'rxjs';
40+
import {tap} from 'rxjs/operators';
4041

41-
import {HttpInterceptorFn} from '../src/interceptor';
42+
import {HTTP_ROOT_INTERCEPTOR_FNS, HttpInterceptorFn} from '../src/interceptor';
4243
import {
4344
HttpFeature,
4445
HttpFeatureKind,
4546
provideHttpClient,
47+
withFetch,
4648
withInterceptors,
4749
withInterceptorsFromDi,
4850
withJsonpSupport,
@@ -375,6 +377,14 @@ describe('provideHttpClient', () => {
375377
});
376378

377379
describe('withRequestsMadeViaParent()', () => {
380+
it('should error when combined with a backend override', () => {
381+
for (const backendFeature of [withFetch(), withXhr()]) {
382+
expect(() => provideHttpClient(withRequestsMadeViaParent(), backendFeature)).toThrowError(
383+
'Configuration error: withRequestsMadeViaParent() cannot be combined with withFetch() or withXhr() in the same call to provideHttpClient().',
384+
);
385+
}
386+
});
387+
378388
for (const backend of ['fetch', 'xhr']) {
379389
describe(`given '${backend}' backend`, () => {
380390
const commonHttpFeatures: HttpFeature<HttpFeatureKind>[] = [];
@@ -452,30 +462,172 @@ describe('provideHttpClient', () => {
452462
req.flush('');
453463
});
454464

455-
it('should be able to connect to a legacy-provided HttpClient context', () => {
465+
it('should include root interceptors in independent child contexts', () => {
456466
TestBed.configureTestingModule({
457-
imports: [HttpClientTestingModule],
458-
providers: [provideLegacyInterceptor('parent')],
467+
providers: [
468+
provideHttpClient(...commonHttpFeatures),
469+
{
470+
provide: HTTP_ROOT_INTERCEPTOR_FNS,
471+
useValue: makeLiteralTagInterceptorFn('root'),
472+
multi: true,
473+
},
474+
provideHttpClientTesting(),
475+
],
459476
});
460477

461478
const child = createEnvironmentInjector(
462479
[
480+
provideHttpClient(withInterceptors([makeLiteralTagInterceptorFn('child')])),
481+
{
482+
provide: HttpBackend,
483+
useFactory: () => inject(HttpBackend, {skipSelf: true}),
484+
},
485+
],
486+
TestBed.inject(EnvironmentInjector),
487+
);
488+
489+
child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
490+
const req = TestBed.inject(HttpTestingController).expectOne('/test');
491+
expect(req.request.headers.get('X-Tag')).toEqual('child,root');
492+
req.flush('');
493+
});
494+
495+
it('should run root interceptors once in the parent request and response chain', () => {
496+
const order: string[] = [];
497+
498+
TestBed.configureTestingModule({
499+
providers: [
463500
provideHttpClient(
464501
...commonHttpFeatures,
502+
withInterceptors([makeOrderedTagInterceptorFn('parent', order)]),
503+
),
504+
{
505+
provide: HTTP_ROOT_INTERCEPTOR_FNS,
506+
useValue: makeOrderedTagInterceptorFn('root', order),
507+
multi: true,
508+
},
509+
provideHttpClientTesting(),
510+
],
511+
});
512+
513+
const child = createEnvironmentInjector(
514+
[
515+
provideHttpClient(
465516
withRequestsMadeViaParent(),
466-
withInterceptors([makeLiteralTagInterceptorFn('child')]),
517+
withInterceptors([makeOrderedTagInterceptorFn('child', order)]),
467518
),
468519
],
469520
TestBed.inject(EnvironmentInjector),
470521
);
471522

472523
child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
473524
const req = TestBed.inject(HttpTestingController).expectOne('/test');
474-
expect(req.request.headers.get('X-Tag')).toEqual('child,parent');
525+
expect(req.request.headers.get('X-Tag')).toEqual('child,parent,root');
526+
expect(order).toEqual(['child:request', 'parent:request', 'root:request']);
475527
req.flush('');
528+
expect(order).toEqual([
529+
'child:request',
530+
'parent:request',
531+
'root:request',
532+
'root:response',
533+
'parent:response',
534+
'child:response',
535+
]);
476536
});
477537
});
478538
}
539+
540+
it('should be able to connect to a legacy-provided HttpClient context', () => {
541+
TestBed.configureTestingModule({
542+
imports: [HttpClientTestingModule],
543+
providers: [provideLegacyInterceptor('parent')],
544+
});
545+
546+
const child = createEnvironmentInjector(
547+
[
548+
provideHttpClient(
549+
withRequestsMadeViaParent(),
550+
withInterceptors([makeLiteralTagInterceptorFn('child')]),
551+
),
552+
],
553+
TestBed.inject(EnvironmentInjector),
554+
);
555+
556+
child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
557+
const req = TestBed.inject(HttpTestingController).expectOne('/test');
558+
expect(req.request.headers.get('X-Tag')).toEqual('child,parent');
559+
req.flush('');
560+
});
561+
562+
it('should inherit root interceptors in independent child contexts', () => {
563+
TestBed.configureTestingModule({
564+
providers: [
565+
provideHttpClient(),
566+
{
567+
provide: HTTP_ROOT_INTERCEPTOR_FNS,
568+
useValue: makeLiteralTagInterceptorFn('root'),
569+
multi: true,
570+
},
571+
provideHttpClientTesting(),
572+
],
573+
});
574+
575+
const delegatingParent = createEnvironmentInjector(
576+
[provideHttpClient(withRequestsMadeViaParent())],
577+
TestBed.inject(EnvironmentInjector),
578+
);
579+
const independentChild = createEnvironmentInjector(
580+
[
581+
provideHttpClient(withInterceptors([makeLiteralTagInterceptorFn('child')])),
582+
{provide: HttpBackend, useValue: TestBed.inject(HttpBackend)},
583+
],
584+
delegatingParent,
585+
);
586+
587+
try {
588+
independentChild.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
589+
const req = TestBed.inject(HttpTestingController).expectOne('/test');
590+
expect(req.request.headers.get('X-Tag')).toEqual('child,root');
591+
req.flush('');
592+
} finally {
593+
independentChild.destroy();
594+
delegatingParent.destroy();
595+
}
596+
});
597+
598+
it('should inherit root interceptors when a custom provider overrides delegation', () => {
599+
TestBed.configureTestingModule({
600+
providers: [
601+
provideHttpClient(),
602+
{
603+
provide: HTTP_ROOT_INTERCEPTOR_FNS,
604+
useValue: makeLiteralTagInterceptorFn('root'),
605+
multi: true,
606+
},
607+
provideHttpClientTesting(),
608+
],
609+
});
610+
611+
const child = createEnvironmentInjector(
612+
[
613+
provideHttpClient(
614+
withRequestsMadeViaParent(),
615+
withInterceptors([makeLiteralTagInterceptorFn('child')]),
616+
),
617+
{provide: HttpBackend, useValue: TestBed.inject(HttpBackend)},
618+
],
619+
TestBed.inject(EnvironmentInjector),
620+
);
621+
622+
try {
623+
child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
624+
const req = TestBed.inject(HttpTestingController).expectOne('/test');
625+
expect(req.request.headers.get('X-Tag')).toEqual('child,root');
626+
req.flush('');
627+
} finally {
628+
child.destroy();
629+
}
630+
});
479631
});
480632

481633
describe('compatibility with Http NgModules', () => {
@@ -666,6 +818,19 @@ function makeLiteralTagInterceptorFn(tag: string): HttpInterceptorFn {
666818
return (req, next) => next(addTagToRequest(req, tag));
667819
}
668820

821+
function makeOrderedTagInterceptorFn(tag: string, order: string[]): HttpInterceptorFn {
822+
return (req, next) => {
823+
order.push(`${tag}:request`);
824+
return next(addTagToRequest(req, tag)).pipe(
825+
tap((event) => {
826+
if (event instanceof HttpResponse) {
827+
order.push(`${tag}:response`);
828+
}
829+
}),
830+
);
831+
};
832+
}
833+
669834
function makeTokenTagInterceptorFn(tag: InjectionToken<string>): HttpInterceptorFn {
670835
return (req, next) => next(addTagToRequest(req, inject(tag)));
671836
}

0 commit comments

Comments
 (0)