Skip to content

Commit 7f35cac

Browse files
committed
feat: Refactor cache-manager-function to use async/await syntax and improve caching options
1 parent 0647831 commit 7f35cac

File tree

1 file changed

+69
-54
lines changed

1 file changed

+69
-54
lines changed

README.md

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

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`.
104

115
## Installation
126

13-
To install the package, use npm or yarn:
7+
Install the package using npm:
148

159
```bash
1610
npm install cache-manager-function
17-
# or
11+
```
12+
13+
or with Yarn:
14+
15+
```bash
1816
yarn add cache-manager-function
1917
```
2018

2119
## Usage
2220

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+
```
2433

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`.
2635

2736
```typescript
28-
import { getOrInitializeCache } from `cache-manager-function`;
37+
const multiply = (x, y) => x * y;
2938

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+
}),
3444
});
45+
46+
// Initializes the cache and caches the result
47+
await cachedMultiply(2, 3);
3548
```
3649

37-
### Caching a Function
50+
### 2. Caching with `cachedFunction`
3851

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

4154
```typescript
42-
import { cachedFunction } from `cache-manager-function`;
55+
type Person = { name: string; lastname: string };
4356

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}!`;
4958

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']
5462
});
5563

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
5966
```
6067

61-
### Using the CacheOptions Decorator
68+
### 3. Using the `CacheOptions` decorator
6269

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

6572
```typescript
6673
import { CacheOptions, cachedFunction } from `cache-manager-function`;
6774

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}`;
7279
}
7380
}
7481

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
7987
```
8088

8189
## API
8290

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

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

87-
- `options`: Configuration for initializing the cache.
100+
### cachedFunction
88101

89-
### `cachedFunction(function_, options?)`
102+
Caches the result of a function based on its arguments.
90103

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

93-
- `function_`: The function to cache.
94-
- `options`: Configuration options for caching.
108+
- **Returns:** A cached function that returns a promise with the result.
95109

96-
### `CacheOptions(selectorOrOptions, ttl?)`
110+
### CacheOptions
97111

98-
A decorator that specifies caching options for the function.
112+
Decorator to cache function results based on selected arguments.
99113

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

103118
## License
104119

105-
MIT License.
120+
MIT License. See the LICENSE file for more details.

0 commit comments

Comments
 (0)