Skip to content

Commit f680695

Browse files
committed
feat(core/http): add server-cache module
1 parent f4b71eb commit f680695

3 files changed

Lines changed: 41 additions & 0 deletions

File tree

packages/core/http/ng-package.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"$schema": "../../../node_modules/ng-packagr/ng-package.schema.json",
3+
"lib": {
4+
"entryFile": "src/public-api.ts"
5+
}
6+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './server-cache';
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { HttpContextToken, HttpInterceptorFn } from '@angular/common/http';
2+
import { inject, InjectionToken, REQUEST_CONTEXT } from '@angular/core';
3+
import { Observable, shareReplay } from 'rxjs';
4+
5+
export class HttpServerCache extends Map<string, Observable<any>> {}
6+
7+
export const HTTP_SERVER_CACHE = new InjectionToken<HttpServerCache | null>(
8+
'HTTP_SERVER_CACHE',
9+
{
10+
factory: () => {
11+
const context = inject(REQUEST_CONTEXT);
12+
if (!context) return null;
13+
if (typeof context !== 'object') return null;
14+
const cache = Reflect.get(context, HttpServerCache.name);
15+
if (!cache) return null;
16+
return cache;
17+
},
18+
},
19+
);
20+
21+
export const HTTP_SERVER_CACHE_KEY = new HttpContextToken<string | null>(
22+
() => null,
23+
);
24+
25+
export const httpServerCacheInterceptor: HttpInterceptorFn = (req, next) => {
26+
const cache = inject(HTTP_SERVER_CACHE);
27+
if (!cache) return next(req);
28+
const key = req.context.get(HTTP_SERVER_CACHE_KEY);
29+
if (!key) return next(req);
30+
if (cache.has(key)) return cache.get(key)!;
31+
const result$ = next(req).pipe(shareReplay(1));
32+
cache.set(key, result$);
33+
return result$;
34+
};

0 commit comments

Comments
 (0)