Skip to content

Commit aff1512

Browse files
alan-agius4dylhunn
authored andcommitted
feat(http): allow HttpClient to cache requests (#49509)
This commit adds a new option for `provideHttpClient` called `withHttpTransferCache()`. When this option is passed, requests done on the server are cached and reused during the bootstrapping of the application in the browser thus avoiding duplicate requests and reducing load time. This is the same as `TransferHttpCacheModule` in https://github.com/angular/universal/blob/main/modules/common/src/transfer_http.ts PR Close #49509
1 parent 8019fed commit aff1512

File tree

4 files changed

+318
-3
lines changed

4 files changed

+318
-3
lines changed

packages/common/http/src/interceptor.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,12 +145,20 @@ function chainedInterceptorFn(
145145
*
146146
* @publicApi
147147
*/
148-
export const HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('HTTP_INTERCEPTORS');
148+
export const HTTP_INTERCEPTORS =
149+
new InjectionToken<HttpInterceptor[]>(ngDevMode ? 'HTTP_INTERCEPTORS' : '');
149150

150151
/**
151152
* A multi-provided token of `HttpInterceptorFn`s.
152153
*/
153-
export const HTTP_INTERCEPTOR_FNS = new InjectionToken<HttpInterceptorFn[]>('HTTP_INTERCEPTOR_FNS');
154+
export const HTTP_INTERCEPTOR_FNS =
155+
new InjectionToken<HttpInterceptorFn[]>(ngDevMode ? 'HTTP_INTERCEPTOR_FNS' : '');
156+
157+
/**
158+
* A multi-provided token of `HttpInterceptorFn`s that are only set in root.
159+
*/
160+
export const HTTP_ROOT_INTERCEPTOR_FNS =
161+
new InjectionToken<HttpInterceptorFn[]>(ngDevMode ? 'HTTP_ROOT_INTERCEPTOR_FNS' : '');
154162

155163
/**
156164
* Creates an `HttpInterceptorFn` which lazily initializes an interceptor chain from the legacy
@@ -184,7 +192,10 @@ export class HttpInterceptorHandler extends HttpHandler {
184192

185193
override handle(initialRequest: HttpRequest<any>): Observable<HttpEvent<any>> {
186194
if (this.chain === null) {
187-
const dedupedInterceptorFns = Array.from(new Set(this.injector.get(HTTP_INTERCEPTOR_FNS)));
195+
const dedupedInterceptorFns = Array.from(new Set([
196+
...this.injector.get(HTTP_INTERCEPTOR_FNS),
197+
...this.injector.get(HTTP_ROOT_INTERCEPTOR_FNS, []),
198+
]));
188199

189200
// Note: interceptors are wrapped right-to-left so that final execution order is
190201
// left-to-right. That is, if `dedupedInterceptorFns` is the array `[a, b, c]`, we want to
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {APP_BOOTSTRAP_LISTENER, ApplicationRef, inject, InjectionToken, makeStateKey, Provider, StateKey, TransferState, ɵInitialRenderPendingTasks as InitialRenderPendingTasks} from '@angular/core';
10+
import {Observable, of} from 'rxjs';
11+
import {first, tap} from 'rxjs/operators';
12+
13+
import {HttpHeaders} from './headers';
14+
import {HTTP_ROOT_INTERCEPTOR_FNS, HttpHandlerFn} from './interceptor';
15+
import {HttpRequest} from './request';
16+
import {HttpEvent, HttpResponse} from './response';
17+
18+
interface TransferHttpResponse {
19+
body: any;
20+
headers: Record<string, string[]>;
21+
status?: number;
22+
statusText?: string;
23+
url?: string;
24+
responseType?: HttpRequest<unknown>['responseType'];
25+
}
26+
27+
const CACHE_STATE = new InjectionToken<{isCacheActive: boolean}>(
28+
ngDevMode ? 'HTTP_TRANSFER_STATE_CACHE_STATE' : '');
29+
30+
/**
31+
* A list of allowed HTTP methods to cache.
32+
*/
33+
const ALLOWED_METHODS = ['GET', 'HEAD'];
34+
35+
export function transferCacheInterceptorFn(
36+
req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
37+
const {isCacheActive} = inject(CACHE_STATE);
38+
39+
// Stop using the cache if the application has stabilized, indicating initial rendering
40+
// is complete.
41+
if (!isCacheActive || !ALLOWED_METHODS.includes(req.method)) {
42+
// Cache is no longer active or method is not HEAD or GET.
43+
// Pass the request through.
44+
return next(req);
45+
}
46+
47+
const transferState = inject(TransferState);
48+
const storeKey = makeCacheKey(req);
49+
const response = transferState.get(storeKey, null);
50+
51+
if (response) {
52+
// Request found in cache. Respond using it.
53+
let body: ArrayBuffer|Blob|string|undefined = response.body;
54+
55+
switch (response.responseType) {
56+
case 'arraybuffer':
57+
body = new TextEncoder().encode(response.body).buffer;
58+
break;
59+
case 'blob':
60+
body = new Blob([response.body]);
61+
break;
62+
}
63+
64+
return of(
65+
new HttpResponse({
66+
body,
67+
headers: new HttpHeaders(response.headers),
68+
status: response.status,
69+
statusText: response.statusText,
70+
url: response.url,
71+
}),
72+
);
73+
}
74+
75+
// Request not found in cache. Make the request and cache it.
76+
return next(req).pipe(
77+
tap((event: HttpEvent<unknown>) => {
78+
if (event instanceof HttpResponse) {
79+
transferState.set<TransferHttpResponse>(storeKey, {
80+
body: event.body,
81+
headers: getHeadersMap(event.headers),
82+
status: event.status,
83+
statusText: event.statusText,
84+
url: event.url || '',
85+
responseType: req.responseType,
86+
});
87+
}
88+
}),
89+
);
90+
}
91+
92+
function getHeadersMap(headers: HttpHeaders): Record<string, string[]> {
93+
const headersMap: Record<string, string[]> = {};
94+
95+
for (const key of headers.keys()) {
96+
const values = headers.getAll(key);
97+
if (values !== null) {
98+
headersMap[key] = values;
99+
}
100+
}
101+
102+
return headersMap;
103+
}
104+
105+
function makeCacheKey(request: HttpRequest<any>): StateKey<TransferHttpResponse> {
106+
// make the params encoded same as a url so it's easy to identify
107+
const {params, method, responseType, url} = request;
108+
const encodedParams = params.keys().sort().map((k) => `${k}=${params.getAll(k)}`).join('&');
109+
const key = method + '.' + responseType + '.' + url + '?' + encodedParams;
110+
111+
const hash = generateHash(key);
112+
113+
return makeStateKey(hash);
114+
}
115+
116+
/**
117+
* A method that returns a hash representation of a string using a variant of DJB2 hash
118+
* algorithm.
119+
*
120+
* This is the same hashing logic that is used to generate component ids.
121+
*/
122+
function generateHash(value: string): string {
123+
let hash = 0;
124+
125+
for (const char of value) {
126+
hash = Math.imul(31, hash) + char.charCodeAt(0) << 0;
127+
}
128+
129+
// Force positive number hash.
130+
// 2147483647 = equivalent of Integer.MAX_VALUE.
131+
hash += 2147483647 + 1;
132+
133+
return hash.toString();
134+
}
135+
136+
/**
137+
* Returns the DI providers needed to enable HTTP transfer cache.
138+
*
139+
* By default, when using server rendering, requests are performed twice: once on the server and
140+
* other one on the browser.
141+
*
142+
* When these providers are added, requests performed on the server are cached and reused during the
143+
* bootstrapping of the application in the browser thus avoiding duplicate requests and reducing
144+
* load time.
145+
*
146+
*/
147+
export function withHttpTransferCache(): Provider[] {
148+
return [
149+
{provide: CACHE_STATE, useValue: {isCacheActive: true}}, {
150+
provide: HTTP_ROOT_INTERCEPTOR_FNS,
151+
useValue: transferCacheInterceptorFn,
152+
multi: true,
153+
deps: [TransferState, CACHE_STATE]
154+
},
155+
{
156+
provide: APP_BOOTSTRAP_LISTENER,
157+
multi: true,
158+
useFactory: () => {
159+
const appRef = inject(ApplicationRef);
160+
const cacheState = inject(CACHE_STATE);
161+
const pendingTasks = inject(InitialRenderPendingTasks);
162+
163+
return () => {
164+
const isStablePromise = appRef.isStable.pipe(first((isStable) => isStable)).toPromise();
165+
const pendingTasksPromise = pendingTasks.whenAllTasksComplete;
166+
167+
Promise.allSettled([isStablePromise, pendingTasksPromise]).then(() => {
168+
cacheState.isCacheActive = false;
169+
});
170+
};
171+
},
172+
deps: [ApplicationRef, CACHE_STATE, InitialRenderPendingTasks]
173+
}
174+
];
175+
}

packages/common/http/test/BUILD.bazel

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ ts_library(
2121
"//packages/common/http/testing",
2222
"//packages/core",
2323
"//packages/core/testing",
24+
"//packages/private/testing",
2425
"@npm//rxjs",
2526
],
2627
)
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {DOCUMENT} from '@angular/common';
10+
import {ApplicationRef, Component} from '@angular/core';
11+
import {makeStateKey, TransferState} from '@angular/core/src/transfer_state';
12+
import {fakeAsync, flush, TestBed} from '@angular/core/testing';
13+
import {withBody} from '@angular/private/testing';
14+
import {BehaviorSubject} from 'rxjs';
15+
16+
import {HttpClient, provideHttpClient} from '../public_api';
17+
import {withHttpTransferCache} from '../src/transfer_cache';
18+
import {HttpTestingController, provideHttpClientTesting} from '../testing';
19+
20+
describe('TransferCache', () => {
21+
@Component({selector: 'test-app-http', template: 'hello'})
22+
class SomeComponent {
23+
}
24+
25+
describe('withHttpTransferCache', () => {
26+
let isStable: BehaviorSubject<boolean>;
27+
28+
function makeRequestAndExpectOne(url: string, body: string): void {
29+
TestBed.inject(HttpClient).get(url).subscribe();
30+
TestBed.inject(HttpTestingController).expectOne(url).flush(body);
31+
}
32+
33+
function makeRequestAndExpectNone(url: string): void {
34+
TestBed.inject(HttpClient).get(url).subscribe();
35+
TestBed.inject(HttpTestingController).expectNone(url);
36+
}
37+
38+
beforeEach(withBody('<test-app-http></test-app-http>', () => {
39+
TestBed.resetTestingModule();
40+
isStable = new BehaviorSubject<boolean>(false);
41+
42+
class ApplicationRefPathed extends ApplicationRef {
43+
override isStable = new BehaviorSubject<boolean>(false);
44+
}
45+
46+
TestBed.configureTestingModule({
47+
declarations: [SomeComponent],
48+
providers: [
49+
{provide: DOCUMENT, useFactory: () => document},
50+
{provide: ApplicationRef, useClass: ApplicationRefPathed},
51+
{provide: ApplicationRef, useClass: ApplicationRefPathed},
52+
withHttpTransferCache(),
53+
provideHttpClient(),
54+
provideHttpClientTesting(),
55+
],
56+
});
57+
58+
const appRef = TestBed.inject(ApplicationRef);
59+
appRef.bootstrap(SomeComponent);
60+
isStable = appRef.isStable as BehaviorSubject<boolean>;
61+
}));
62+
63+
it('should store HTTP calls in cache when application is not stable', () => {
64+
makeRequestAndExpectOne('/test', 'foo');
65+
const key = makeStateKey('432906284');
66+
const transferState = TestBed.inject(TransferState);
67+
expect(transferState.get(key, null)).toEqual(jasmine.objectContaining({body: 'foo'}));
68+
});
69+
70+
it('should stop storing HTTP calls in `TransferState` after application becomes stable',
71+
fakeAsync(() => {
72+
makeRequestAndExpectOne('/test-1', 'foo');
73+
makeRequestAndExpectOne('/test-2', 'buzz');
74+
75+
isStable.next(true);
76+
77+
flush();
78+
79+
makeRequestAndExpectOne('/test-3', 'bar');
80+
81+
const transferState = TestBed.inject(TransferState);
82+
expect(JSON.parse(transferState.toJson()) as Record<string, unknown>).toEqual({
83+
'3706062792': {
84+
'body': 'foo',
85+
'headers': {},
86+
'status': 200,
87+
'statusText': 'OK',
88+
'url': '/test-1',
89+
'responseType': 'json'
90+
},
91+
'3706062823': {
92+
'body': 'buzz',
93+
'headers': {},
94+
'status': 200,
95+
'statusText': 'OK',
96+
'url': '/test-2',
97+
'responseType': 'json'
98+
}
99+
});
100+
}));
101+
102+
it(`should use calls from cache when present and application is not stable`, () => {
103+
makeRequestAndExpectOne('/test-1', 'foo');
104+
// Do the same call, this time it should served from cache.
105+
makeRequestAndExpectNone('/test-1');
106+
});
107+
108+
it(`should not use calls from cache when present and application is stable`, fakeAsync(() => {
109+
makeRequestAndExpectOne('/test-1', 'foo');
110+
111+
isStable.next(true);
112+
flush();
113+
// Do the same call, this time it should go through as application is stable.
114+
makeRequestAndExpectOne('/test-1', 'foo');
115+
}));
116+
117+
it(`should differentiate calls with different parameters`, async () => {
118+
// make calls with different parameters. All of which should be saved in the state.
119+
makeRequestAndExpectOne('/test-1?foo=1', 'foo');
120+
makeRequestAndExpectOne('/test-1', 'foo');
121+
makeRequestAndExpectOne('/test-1?foo=2', 'buzz');
122+
123+
makeRequestAndExpectNone('/test-1?foo=1');
124+
await expectAsync(TestBed.inject(HttpClient).get('/test-1?foo=1').toPromise())
125+
.toBeResolvedTo('foo');
126+
});
127+
});
128+
});

0 commit comments

Comments
 (0)