Skip to content

Commit 0647831

Browse files
committed
feat: Refactor cachedFunction to use selectorToCacheKey
1 parent f820891 commit 0647831

File tree

3 files changed

+76
-70
lines changed

3 files changed

+76
-70
lines changed

README.md

Lines changed: 53 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,116 +1,105 @@
1-
# cache-manager-function
1+
# Cache Manager Function
22

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.
44

55
## Features
66

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.
1210

1311
## Installation
1412

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
1719
```
1820

1921
## Usage
2022

21-
### 1. Initialize Cache Manager
23+
### Initialize Cache
2224

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.
2426

2527
```typescript
26-
import { initializeCache } from 'cache-manager-function';
28+
import { getOrInitializeCache } from `cache-manager-function`;
2729

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 },
3234
});
3335
```
3436

35-
### 2. Caching Functions with `cacheFunction`
37+
### Caching a Function
3638

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.
3840

3941
```typescript
40-
import { cacheFunction } from 'cache-manager-function';
42+
import { cachedFunction } from `cache-manager-function`;
4143

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}`;
4448
}
4549

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
4954
});
5055

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`
5259
```
5360

54-
### 3. Using `@cache` Decorator for Class Methods
61+
### Using the CacheOptions Decorator
5562

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.
5764

5865
```typescript
59-
import { cache } from 'cache-manager-function';
66+
import { CacheOptions, cachedFunction } from `cache-manager-function`;
6067

6168
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}`;
6572
}
6673
}
6774

6875
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`
8579
```
8680

8781
## API
8882

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)`
9684

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.
9886

99-
- **function_**: The function to be cached.
100-
- **options**: Configuration options including `ttl` and `keySelector`.
87+
- `options`: Configuration for initializing the cache.
10188

102-
### `@cache(options: CacheOptions)`
89+
### `cachedFunction(function_, options?)`
10390

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.
10592

106-
- **options**: Configuration object with `ttl` and `keySelector`.
93+
- `function_`: The function to cache.
94+
- `options`: Configuration options for caching.
10795

108-
### `@cacheMeta(options: CacheOptions)`
96+
### `CacheOptions(selectorOrOptions, ttl?)`
10997

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.
11199

112-
- **options**: Configuration object with `ttl` and `keySelector`.
100+
- `selectorOrOptions`: Selector or options for caching.
101+
- `ttl`: Time-to-live in seconds.
113102

114103
## License
115104

116-
This library is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
105+
MIT License.

src/index.ts

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable @typescript-eslint/naming-convention */
12

23
/* eslint-disable @typescript-eslint/no-explicit-any */
34

@@ -104,15 +105,31 @@ export function cachedFunction<F extends CacheableFunction>(function_: F, option
104105
}
105106

106107
/**
107-
* Specify the options used when `cachedFunction` is invoked with this function.
108-
* The decorator arguments take precedence over the options provided to `cachedFunction`.
108+
* Decorator for caching the result of a function based on selected arguments.
109+
*
110+
* This overload allows specifying the arguments that will be used to generate the cache key, and optionally a TTL (time to live).
111+
*
112+
* @template F - The type of the cacheable function.
113+
* @param {ArgumentPaths<F>} selector - The paths of the arguments to include in the cache key.
114+
* This specifies which function arguments will be considered when generating the cache key.
115+
* @param {number} [ttl] - Optional time to live (TTL) in seconds for the cached value.
116+
* If not provided, the cached value will persist until it is evicted based on the cache settings.
117+
* @returns {Function} A decorator function that adds caching options to the method's descriptor.
118+
*/
119+
export function CacheOptions<F extends CacheableFunction>(selector: ArgumentPaths<F>, ttl?: number): any;
120+
121+
/**
122+
* Decorator for caching the result of a function.
123+
*
124+
* This overload allows providing a complete configuration object that specifies all caching behaviors,
125+
* including which arguments to use for the cache key, the TTL, etc.
109126
*
110127
* @template F - The type of the cacheable function.
111-
* @param {ArgumentPaths<F> | CachedFunctionOptions<F>} selectorOrOptions - The selector or options for caching.
112-
* @param {number} [ttl] - The time-to-live (TTL) for the cache.
113-
* @returns {any} - The modified descriptor object.
128+
* @param {CachedFunctionOptions<F>} options - The full configuration options for caching the function.
114129
*/
115-
export function CacheOptions<F extends CacheableFunction>( // eslint-disable-line @typescript-eslint/naming-convention
130+
export function CacheOptions<F extends CacheableFunction>(options: CachedFunctionOptions<F>): any;
131+
132+
export function CacheOptions<F extends CacheableFunction>(
116133
selectorOrOptions: ArgumentPaths<F> | CachedFunctionOptions<F>,
117134
ttl?: number,
118135
): any {
File renamed without changes.

0 commit comments

Comments
 (0)