|
1 |
| -# Cache Manager Function |
| 1 | +# cache-manager-function |
2 | 2 |
|
3 |
| -A TypeScript utility package to easily cache function results using `cache-manager`. It provides a set of functions and decorators to cache the output of functions and retrieve results from the cache for faster performance. |
4 |
| - |
5 |
| -## Features |
6 |
| - |
7 |
| -- **Easy cache initialization**: Automatically manages cache initialization and configuration. |
8 |
| -- **Flexible caching**: Allows fine-grained control over cache key generation and TTL (time-to-live). |
9 |
| -- **Decorator support**: Simplify caching configurations with the `@CacheOptions` decorator. |
| 3 | +`cache-manager-function` provides utilities to cache the outputs of functions based on their arguments using `cache-manager`. |
10 | 4 |
|
11 | 5 | ## Installation
|
12 | 6 |
|
13 |
| -To install the package, use npm or yarn: |
| 7 | +Install the package using npm: |
14 | 8 |
|
15 | 9 | ```bash
|
16 | 10 | npm install cache-manager-function
|
17 |
| -# or |
| 11 | +``` |
| 12 | + |
| 13 | +or with Yarn: |
| 14 | + |
| 15 | +```bash |
18 | 16 | yarn add cache-manager-function
|
19 | 17 | ```
|
20 | 18 |
|
21 | 19 | ## Usage
|
22 | 20 |
|
23 |
| -### Initialize Cache |
| 21 | +### 1. Initialize |
| 22 | + |
| 23 | +Call `getOrInitializeCache` to manually initialize the cache. |
| 24 | + |
| 25 | +```typescript |
| 26 | +const cache = await getOrInitializeCache<RedisStore>({ |
| 27 | + store: await redisStore({ |
| 28 | + host: 'localhost', |
| 29 | + port: 6379, |
| 30 | + }), |
| 31 | +}); |
| 32 | +``` |
24 | 33 |
|
25 |
| -Before using the caching functions, you need to initialize the cache. |
| 34 | +Alternatively, you can initialize the cache implicitly by providing the store directly to `cachedFunction`. |
26 | 35 |
|
27 | 36 | ```typescript
|
28 |
| -import { getOrInitializeCache } from `cache-manager-function`; |
| 37 | +const multiply = (x, y) => x * y; |
29 | 38 |
|
30 |
| -// Initialize the cache with your store and configuration options. |
31 |
| -await getOrInitializeCache({ |
32 |
| - store: { create: () => /* your store logic */ }, |
33 |
| - config: { ttl: 60 }, |
| 39 | +const cachedMultiply = cachedFunction(multiply, { |
| 40 | + store: await redisStore({ |
| 41 | + host: 'localhost', |
| 42 | + port: 6379, |
| 43 | + }), |
34 | 44 | });
|
| 45 | + |
| 46 | +// Initializes the cache and caches the result |
| 47 | +await cachedMultiply(2, 3); |
35 | 48 | ```
|
36 | 49 |
|
37 |
| -### Caching a Function |
| 50 | +### 2. Caching with `cachedFunction` |
38 | 51 |
|
39 |
| -You can cache the result of a function using the `cachedFunction` wrapper. |
| 52 | +The `selector` option specifies which arguments should be used to generate the cache key. |
40 | 53 |
|
41 | 54 | ```typescript
|
42 |
| -import { cachedFunction } from `cache-manager-function`; |
| 55 | +type Person = { name: string; lastname: string }; |
43 | 56 |
|
44 |
| -// Define a function you want to cache |
45 |
| -async function fetchData(id: number): Promise<string> { |
46 |
| - // Simulate an API call or some expensive operation |
47 |
| - return `Data for ${id}`; |
48 |
| -} |
| 57 | +const greet = (person: Person) => `Hello, ${person.name} ${person.lastname}!`; |
49 | 58 |
|
50 |
| -// Create a cached version of the function |
51 |
| -const cachedFetchData = cachedFunction(fetchData, { |
52 |
| - selector: [`0`], // Cache key based on the first argument (id) |
53 |
| - ttl: 120, // Cache the result for 120 seconds |
| 59 | +// Caches based on `person.name` and `person.lastname` |
| 60 | +const cachedGreet = cachedFunction(greet, { |
| 61 | + selector: ['0.name', '0.lastname'] |
54 | 62 | });
|
55 | 63 |
|
56 |
| -// Use the cached function |
57 |
| -const data = await cachedFetchData(1); |
58 |
| -console.log(data); // Outputs: `Data for 1` |
| 64 | +await cachedGreet({ person: { name: `John`, lastname: `Doe` } }); // Caches the result based on name=John and lastname=Doe |
| 65 | +await cachedGreet({ person: { name: `Jane`, lastname: `Doe` } }); // Caches the result based on name=Jane and lastname=Doe |
59 | 66 | ```
|
60 | 67 |
|
61 |
| -### Using the CacheOptions Decorator |
| 68 | +### 3. Using the `CacheOptions` decorator |
62 | 69 |
|
63 |
| -You can specify caching options directly on the function using the `@CacheOptions` decorator. |
| 70 | +`CacheOptions` receives the exact same options that `cachedFunction` receives. It’s an alternative way to define the cache behavior directly on the function. |
64 | 71 |
|
65 | 72 | ```typescript
|
66 | 73 | import { CacheOptions, cachedFunction } from `cache-manager-function`;
|
67 | 74 |
|
68 |
| -class DataService { |
69 |
| - @CacheOptions([`0`], 180) // Cache for 180 seconds based on the first argument |
70 |
| - async getData(id: number): Promise<string> { |
71 |
| - return `Service Data for ${id}`; |
| 75 | +class UserService { |
| 76 | + @CacheOptions(['0'], 300) // Specifies to cache based on the first argument (id), with a TTL of 300ms |
| 77 | + async getUser(id: number) { |
| 78 | + return `User with ID: ${id}`; |
72 | 79 | }
|
73 | 80 | }
|
74 | 81 |
|
75 |
| -const service = new DataService(); |
76 |
| -const cachedGetData = cachedFunction(service.getData.bind(service)); |
77 |
| -const result = await cachedGetData(2); |
78 |
| -console.log(result); // Outputs: `Service Data for 2` |
| 82 | +const service = new UserService(); |
| 83 | +const cachedFetchUser = cachedFunction(service.getUser); |
| 84 | + |
| 85 | +await userService.getUser(1); // Executes and caches based on the `id` argument |
| 86 | +await userService.getUser(1); // Returns the cached result |
79 | 87 | ```
|
80 | 88 |
|
81 | 89 | ## API
|
82 | 90 |
|
83 |
| -### `getOrInitializeCache(options?: CachedFunctionInitializerOptions)` |
| 91 | +### getOrInitializeCache |
| 92 | + |
| 93 | +Initializes or retrieves the cache. |
| 94 | + |
| 95 | +- **Parameters:** |
| 96 | + - `options` (Optional): Configuration options to initialize the cache. |
84 | 97 |
|
85 |
| -Retrieves or initializes the cache. Throws an error if the cache is not initialized and no options are provided. |
| 98 | +- **Returns:** A promise that resolves to the cache instance. |
86 | 99 |
|
87 |
| -- `options`: Configuration for initializing the cache. |
| 100 | +### cachedFunction |
88 | 101 |
|
89 |
| -### `cachedFunction(function_, options?)` |
| 102 | +Caches the result of a function based on its arguments. |
90 | 103 |
|
91 |
| -Caches the result of a function. Returns the cached value if available, otherwise executes the function and caches the result. |
| 104 | +- **Parameters:** |
| 105 | + - `function_`: The function to cache. |
| 106 | + - `options` (Optional): Configuration options for caching. |
92 | 107 |
|
93 |
| -- `function_`: The function to cache. |
94 |
| -- `options`: Configuration options for caching. |
| 108 | +- **Returns:** A cached function that returns a promise with the result. |
95 | 109 |
|
96 |
| -### `CacheOptions(selectorOrOptions, ttl?)` |
| 110 | +### CacheOptions |
97 | 111 |
|
98 |
| -A decorator that specifies caching options for the function. |
| 112 | +Decorator to cache function results based on selected arguments. |
99 | 113 |
|
100 |
| -- `selectorOrOptions`: Selector or options for caching. |
101 |
| -- `ttl`: Time-to-live in seconds. |
| 114 | +- **Parameters:** |
| 115 | + - `selector`: Paths of the arguments to include in the cache key. |
| 116 | + - `ttl` (Optional): Time-to-live for the cached result. |
102 | 117 |
|
103 | 118 | ## License
|
104 | 119 |
|
105 |
| -MIT License. |
| 120 | +MIT License. See the LICENSE file for more details. |
0 commit comments