Skip to content

Commit

Permalink
fix(@nguniversal/common): avoid invalidating cache when using a post …
Browse files Browse the repository at this point in the history
…request

Currently, when using a post request the TransferHttpCache is invalidated, this is on the assumption that POST will mutate the previous GET requests. This however is very rare.

Closes #1795
  • Loading branch information
alan-agius4 committed Feb 21, 2023
1 parent 858ca5c commit 93c8a38
Showing 1 changed file with 9 additions and 24 deletions.
33 changes: 9 additions & 24 deletions modules/common/src/transfer_http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,9 @@ import {
HttpResponse,
} from '@angular/common/http';
import { ApplicationRef, Injectable, NgModule } from '@angular/core';
import {
BrowserTransferStateModule,
StateKey,
TransferState,
makeStateKey,
} from '@angular/platform-browser';
import { StateKey, TransferState, makeStateKey } from '@angular/platform-browser';
import { Observable, of as observableOf } from 'rxjs';
import { filter, take, tap } from 'rxjs/operators';
import { defaultIfEmpty, first, tap } from 'rxjs/operators';

type ResponseType = HttpRequest<unknown>['responseType'];

Expand Down Expand Up @@ -53,12 +48,6 @@ function getHeadersMap(headers: HttpHeaders): Record<string, string[]> {
export class TransferHttpCacheInterceptor implements HttpInterceptor {
private isCacheActive = true;

private invalidateCacheEntry(url: string) {
Object.keys(this.transferState['store']).forEach((key) =>
key.includes(url) ? this.transferState.remove(makeStateKey(key)) : null,
);
}

private makeCacheKey(
method: string,
url: string,
Expand All @@ -82,23 +71,18 @@ export class TransferHttpCacheInterceptor implements HttpInterceptor {
// complete.
appRef.isStable
.pipe(
filter((isStable: boolean) => isStable),
take(1),
first((isStable) => isStable),
defaultIfEmpty(false),
)
.subscribe(() => {
this.isCacheActive = false;
});
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Stop using the cache if there is a mutating call.
if (req.method !== 'GET' && req.method !== 'HEAD') {
this.isCacheActive = false;
this.invalidateCacheEntry(req.url);
}

if (!this.isCacheActive) {
// Cache is no longer active. Pass the request through.
if (!this.isCacheActive || (req.method !== 'GET' && req.method !== 'HEAD')) {
// Cache is no longer active or method is not HEAD or GET.
// Pass the request through.
return next.handle(req);
}

Expand Down Expand Up @@ -154,8 +138,9 @@ export class TransferHttpCacheInterceptor implements HttpInterceptor {
* calls from the server to the client application.
*/
@NgModule({
imports: [BrowserTransferStateModule],
providers: [
ApplicationRef,
TransferState,
TransferHttpCacheInterceptor,
{ provide: HTTP_INTERCEPTORS, useExisting: TransferHttpCacheInterceptor, multi: true },
],
Expand Down

0 comments on commit 93c8a38

Please sign in to comment.