|
1 |
| -# cache-manager-function |
| 1 | +# Cache Manager Function |
2 | 2 |
|
3 |
| -`cache-manager-function` is a vertical integration library that extends `cache-manager` to provide easy-to-use function-level caching with support for Redis and other stores. It allows you to cache function results with decorators, automatic cache initialization, and customizable cache key selection strategies. |
| 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 | 4 |
|
5 | 5 | ## Features
|
6 | 6 |
|
7 |
| -- **Function Caching**: Easily cache async functions to improve performance. |
8 |
| -- **Class Method Caching**: Use decorators to add caching to class methods. |
9 |
| -- **Custom Key Selection**: Dynamically generate cache keys using functions, strings, or paths. |
10 |
| -- **TTL Management**: Set cache expiration times to keep your data fresh. |
11 |
| -- **Seamless Integration**: Built on top of `cache-manager` for reliable and configurable caching. |
| 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. |
12 | 10 |
|
13 | 11 | ## Installation
|
14 | 12 |
|
15 |
| -```shell |
16 |
| -npm install cache-manager-function cache-manager cache-manager-redis-store |
| 13 | +To install the package, use npm or yarn: |
| 14 | + |
| 15 | +```bash |
| 16 | +npm install cache-manager-function |
| 17 | +# or |
| 18 | +yarn add cache-manager-function |
17 | 19 | ```
|
18 | 20 |
|
19 | 21 | ## Usage
|
20 | 22 |
|
21 |
| -### 1. Initialize Cache Manager |
| 23 | +### Initialize Cache |
22 | 24 |
|
23 |
| -Before using caching, initialize the cache manager with your desired configuration. By default, it uses Redis as the cache store. |
| 25 | +Before using the caching functions, you need to initialize the cache. |
24 | 26 |
|
25 | 27 | ```typescript
|
26 |
| -import { initializeCache } from 'cache-manager-function'; |
| 28 | +import { getOrInitializeCache } from `cache-manager-function`; |
27 | 29 |
|
28 |
| -await initializeCache({ |
29 |
| - host: 'localhost', |
30 |
| - port: 6379, |
31 |
| - ttl: 60, // Time-to-live in seconds |
| 30 | +// Initialize the cache with your store and configuration options. |
| 31 | +await getOrInitializeCache({ |
| 32 | + store: { create: () => /* your store logic */ }, |
| 33 | + config: { ttl: 60 }, |
32 | 34 | });
|
33 | 35 | ```
|
34 | 36 |
|
35 |
| -### 2. Caching Functions with `cacheFunction` |
| 37 | +### Caching a Function |
36 | 38 |
|
37 |
| -Wrap your async functions with `cacheFunction` to automatically cache their results. |
| 39 | +You can cache the result of a function using the `cachedFunction` wrapper. |
38 | 40 |
|
39 | 41 | ```typescript
|
40 |
| -import { cacheFunction } from 'cache-manager-function'; |
| 42 | +import { cachedFunction } from `cache-manager-function`; |
41 | 43 |
|
42 |
| -async function fetchData(id) { |
43 |
| - // Fetch data logic |
| 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}`; |
44 | 48 | }
|
45 | 49 |
|
46 |
| -const cachedFetchData = cacheFunction(fetchData, { |
47 |
| - ttl: 120, |
48 |
| - keySelector: ['id'], |
| 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 |
49 | 54 | });
|
50 | 55 |
|
51 |
| -const result = await cachedFetchData(123); |
| 56 | +// Use the cached function |
| 57 | +const data = await cachedFetchData(1); |
| 58 | +console.log(data); // Outputs: `Data for 1` |
52 | 59 | ```
|
53 | 60 |
|
54 |
| -### 3. Using `@cache` Decorator for Class Methods |
| 61 | +### Using the CacheOptions Decorator |
55 | 62 |
|
56 |
| -Use the `@cache` decorator to cache class methods with customizable TTL and key selection. |
| 63 | +You can specify caching options directly on the function using the `@CacheOptions` decorator. |
57 | 64 |
|
58 | 65 | ```typescript
|
59 |
| -import { cache } from 'cache-manager-function'; |
| 66 | +import { CacheOptions, cachedFunction } from `cache-manager-function`; |
60 | 67 |
|
61 | 68 | class DataService {
|
62 |
| - @cache({ ttl: 180, keySelector: 'id' }) |
63 |
| - async getData(id) { |
64 |
| - // Fetch data logic |
| 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}`; |
65 | 72 | }
|
66 | 73 | }
|
67 | 74 |
|
68 | 75 | const service = new DataService();
|
69 |
| -const data = await service.getData(123); |
70 |
| -``` |
71 |
| - |
72 |
| -### 4. Using `@cacheMeta` for Metadata |
73 |
| - |
74 |
| -The `@cacheMeta` decorator sets up metadata for caching, specifying how cache keys and TTLs are handled. This metadata can be used by other mechanisms to manage caching behavior. |
75 |
| - |
76 |
| -```typescript |
77 |
| -import { cacheMeta } from 'cache-manager-function'; |
78 |
| - |
79 |
| -class UserService { |
80 |
| - @cacheMeta({ ttl: 60, keySelector: ['userId'] }) |
81 |
| - async getUser(userId) { |
82 |
| - // Method logic |
83 |
| - } |
84 |
| -} |
| 76 | +const cachedGetData = cachedFunction(service.getData.bind(service)); |
| 77 | +const result = await cachedGetData(2); |
| 78 | +console.log(result); // Outputs: `Service Data for 2` |
85 | 79 | ```
|
86 | 80 |
|
87 | 81 | ## API
|
88 | 82 |
|
89 |
| -### `initializeCache(config: CacheInitializationConfig): Promise<void>` |
90 |
| - |
91 |
| -Initializes the cache manager with the specified configuration. |
92 |
| - |
93 |
| -- **config**: Configuration object with optional `host`, `port`, `password`, and required `ttl`. |
94 |
| - |
95 |
| -### `cacheFunction(function_, options): Function` |
| 83 | +### `getOrInitializeCache(options?: CachedFunctionInitializerOptions)` |
96 | 84 |
|
97 |
| -Wraps and caches an async function based on the provided options. |
| 85 | +Retrieves or initializes the cache. Throws an error if the cache is not initialized and no options are provided. |
98 | 86 |
|
99 |
| -- **function_**: The function to be cached. |
100 |
| -- **options**: Configuration options including `ttl` and `keySelector`. |
| 87 | +- `options`: Configuration for initializing the cache. |
101 | 88 |
|
102 |
| -### `@cache(options: CacheOptions)` |
| 89 | +### `cachedFunction(function_, options?)` |
103 | 90 |
|
104 |
| -A decorator to cache class methods. |
| 91 | +Caches the result of a function. Returns the cached value if available, otherwise executes the function and caches the result. |
105 | 92 |
|
106 |
| -- **options**: Configuration object with `ttl` and `keySelector`. |
| 93 | +- `function_`: The function to cache. |
| 94 | +- `options`: Configuration options for caching. |
107 | 95 |
|
108 |
| -### `@cacheMeta(options: CacheOptions)` |
| 96 | +### `CacheOptions(selectorOrOptions, ttl?)` |
109 | 97 |
|
110 |
| -Adds caching metadata to methods for defining cache keys and TTL without direct caching. |
| 98 | +A decorator that specifies caching options for the function. |
111 | 99 |
|
112 |
| -- **options**: Configuration object with `ttl` and `keySelector`. |
| 100 | +- `selectorOrOptions`: Selector or options for caching. |
| 101 | +- `ttl`: Time-to-live in seconds. |
113 | 102 |
|
114 | 103 | ## License
|
115 | 104 |
|
116 |
| -This library is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. |
| 105 | +MIT License. |
0 commit comments