Skip to content

Commit 7c12529

Browse files
committed
perf(endpoints): add memoization to useEndpoints
1 parent e05c594 commit 7c12529

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

packages/endpoints/src/convenience.ts

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
1-
import { inject, InjectionToken } from '@angular/core';
1+
import { inject, Injectable, InjectionToken } from '@angular/core';
22

33
import { EndpointSchemas } from './core';
44
import { GenerateEndpoints, generateEndpoints } from './generators';
55
import { EndpointInvoker } from './invoker';
66

7+
@Injectable({ providedIn: 'root' })
8+
export class EndpointsWeakMap extends WeakMap<
9+
EndpointSchemas,
10+
GenerateEndpoints<EndpointSchemas>
11+
> {}
12+
713
/**
8-
* Convenience function that generates invocable endpoint functions
9-
* from the given endpoint schemas.
14+
* Creates a collection of endpoints generated from the given schemas,
15+
* through `generateEndpoints`, memoizing the result for future invocations.
1016
*
1117
* @see `generateEndpoints` - for manually generating endpoints
1218
*
@@ -23,12 +29,18 @@ import { EndpointInvoker } from './invoker';
2329
export const useEndpoints = <Schemas extends EndpointSchemas>(
2430
schemas: Schemas,
2531
invoker = inject(EndpointInvoker),
26-
): GenerateEndpoints<Schemas> => generateEndpoints(invoker, schemas);
32+
memoizer = inject(EndpointsWeakMap),
33+
): GenerateEndpoints<Schemas> => {
34+
if (memoizer.has(schemas))
35+
return memoizer.get(schemas)! as GenerateEndpoints<Schemas>;
36+
const endpoints = generateEndpoints(invoker, schemas);
37+
memoizer.set(schemas, endpoints as GenerateEndpoints<EndpointSchemas>);
38+
return endpoints;
39+
};
2740

2841
/**
29-
* Convenience function that creates a typed `InjectionToken` with a default
30-
* value of a collection of endpoints generated from the given schemas,
31-
* through `generateEndpoints`.
42+
* Creates a typed `InjectionToken` with a default value of a collection of
43+
* endpoints generated from the given schemas, through `generateEndpoints`.
3244
*
3345
* @see `generateEndpoints` - for manually generating endpoints
3446
* @see `createEndpointsFactory` - lower-level convenience function

0 commit comments

Comments
 (0)