Skip to content

Commit 2540141

Browse files
Merge pull request #66 from DBB-Software/feat/issue-1648
feat: improved cache revalidation and configuring handler
2 parents 1adee84 + 92a3192 commit 2540141

File tree

14 files changed

+303
-228
lines changed

14 files changed

+303
-228
lines changed

README.md

Lines changed: 48 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
# Next-Cache-Handler
32

43
## Introduction
@@ -35,21 +34,25 @@ yarn add @dbbs/next-cache-handler-core
3534

3635
### Configuration
3736
Create a `cacheHandler.js` in your project and configure as follows:
38-
```javascript
39-
import { Cache, FileSystemCache } from '@dbbs/next-cache-handler-core'
37+
```typescript
38+
import { Cache, FileSystemCache, ConsoleLogger } from '@dbbs/next-cache-handler-core'
39+
40+
const config = {
41+
cacheCookies: ['my-cookie-1', 'my-cookie-2'],
42+
cacheQueries: ['my-query-1', 'my-query-2'],
43+
enableDeviceSplit: true,
44+
noCacheMatchers: [],
45+
cache: new FileSystemCache(),
46+
logger: new ConsoleLogger()
47+
}
4048

41-
Cache
42-
.setCacheStrategy(new FileSystemCache())
43-
.addCookies(['my-cookie-1','my-cookie-2'])
44-
.addQueries(['my-query-1','my-query-2'])
45-
.addDeviceSplit()
46-
// Additional configuration...
49+
Cache.setConfig(config)
4750
export default Cache
4851
```
4952

5053
Update your `next.config.js` to use the cache handler.
5154

52-
```
55+
```typescript
5356
const nextConfig = {
5457
cacheHandler: require.resolve('./cacheHandler.js')
5558
}
@@ -60,12 +63,12 @@ export default nextConfig
6063
## Cache Strategies
6164
Explore various caching strategies to find the best fit for your application's needs:
6265
- **MemoryCache**: Ideal for short-lived data in applications with limited cache size requirements. By default limit of size is set to 512MB.
63-
```
66+
```typescript
6467
import { Cache, MemoryCache } from '@dbbs/next-cache-handler-core'
6568

6669
Cache.setCacheStrategy(new MemoryCache())
6770
```
68-
```
71+
```typescript
6972
import { Cache, MemoryCache } from '@dbbs/next-cache-handler-core'
7073

7174
// extending size limitation to 1024MB.
@@ -78,7 +81,7 @@ import { Cache, FileSystemCache } from '@dbbs/next-cache-handler-core'
7881
Cache.setCacheStrategy(new FileSystemCache())
7982
```
8083
- **Redis**: Perfect for distributed applications requiring shared cache access.
81-
```
84+
```typescript
8285
import { Cache } from '@dbbs/next-cache-handler-core'
8386
import { RedisCache } from '@dbbs/next-cache-handler-redis'
8487

@@ -94,7 +97,7 @@ Cache.setCacheStrategy(new RedisCache(redisConnectionOpts))
9497
By default, we use plain Redis as the cache store.
9598
But you are able to use Redis with RedisJSON and RedisSearch modules as the cache store.
9699
In that case you need to pass extra params to RedisCache class during initialization.
97-
```
100+
```typescript
98101
import { Cache } from '@dbbs/next-cache-handler-core'
99102
import { RedisCache, RedisStrategy } from "@dbbs/next-cache-handler-redis"
100103

@@ -104,56 +107,54 @@ const redisConnectionOpts = {
104107
...
105108
}
106109

107-
Cache.setCacheStrategy(new RedisCache(redisConnectionOpts, RedisStrategy.RedisStack))))
110+
Cache.setConfig({
111+
...config,
112+
cache: new RedisCache(redisConnectionOpts, RedisStrategy.RedisJSON),
113+
})
108114
```
109115
- **S3**: Suitable for high scalable applications.
110-
```
116+
```typescript
111117
import { Cache } from '@dbbs/next-cache-handler-core'
112118
import { S3Cache } from '@dbbs/next-cache-handler-s3'
113119

114-
Cache.setCacheStrategy(new S3Cache('cache-bucket-name'))
120+
Cache.setConfig({
121+
...config,
122+
cache: new S3Cache('cache-bucket-name'),
123+
})
115124
```
116125

117126
## API Reference
118127

119-
### `addCookies`
120-
Cookie names what is going to be used to fragmentate cache based on browser cookies session.
121-
```
122-
Cache.addCookies(['my-cookie-to-split'])
123-
```
128+
### Configuration Options
129+
The cache handler accepts the following configuration options:
124130

125-
### `addQueries`
126-
Query names to fragmentate cache based on url query parameters.
127-
```
128-
Cache.addQueries(['my-query-to-split'])
129-
```
131+
- `cacheCookies`: Array of cookie names to use for cache segmentation
132+
- `cacheQueries`: Array of query parameter names to use for cache segmentation
133+
- `enableDeviceSplit`: Boolean to enable/disable device-based cache segmentation
134+
- `noCacheMatchers`: Array of path patterns to exclude from caching
135+
- `cache`: Cache strategy instance (FileSystemCache, MemoryCache, etc.)
136+
- `logger`: Logger instance implementing the BaseLogger interface
130137

131-
### `addDeviceSplit`
132-
Enables to fragmentate experience based on current `User-Agent` of the request.
133-
```
134-
Cache.addDeviceSplit()
135-
```
138+
```typescript
139+
import { Cache, FileSystemCache } from '@dbbs/next-cache-handler-core'
136140

137-
### `setCacheStrategy`
138-
Applies given strategy to cache page data.
139-
```
140-
Cache.setCacheStrategy(new MemoryCache())
141-
```
141+
const config = {
142+
cacheCookies: ['my-cookie-1', 'my-cookie-2'],
143+
cacheQueries: ['my-query-1', 'my-query-2'],
144+
enableDeviceSplit: true,
145+
noCacheMatchers: [],
146+
cache: new FileSystemCache(),
147+
logger: new ConsoleLogger()
148+
}
142149

143-
### `addNoCacheMatchers`
144-
This allows you to exclude pages for which caching should be disabled.
145-
You can match one or more paths using array syntax. The matcher config allows full regex.
146-
Add route to ignore cache list. All routes added here would be excluded from caching and will always render again.
147-
```
148-
Cache.addNoCacheMatchers('/home')
149-
Cache.addNoCacheMatchers(['/home','/about'])
150-
Cache.addNoCacheMatchers('/catalog/:page')
150+
Cache.setConfig(config)
151+
152+
export default Cache
151153
```
152-
Read more details on [path-to-regexp](https://github.com/pillarjs/path-to-regexp#path-to-regexp-1) documentation.
153154

154155
## Logging
155156
Leverage the built-in logger for monitoring cache operations or integrate your custom logger for advanced logging capabilities.
156-
```
157+
```typescript
157158
import { BaseLogger, Cache, FileSystemCache } from '@dbbs/next-cache-handler-core'
158159

159160
class MyCustomLogger implements BaseLogger {

examples/app-router/cacheHandler.mjs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { Cache, FileSystemCache } from '@dbbs/next-cache-handler-core'
22

3-
Cache.addCookies(['abtest']).addQueries(['abtest']).setCacheStrategy(new FileSystemCache()).addDeviceSplit()
3+
Cache.setConfig({
4+
enableDeviceSplit: true,
5+
cacheCookies: ['abtest'],
6+
cacheQueries: ['abtest'],
7+
cache: new FileSystemCache()
8+
})
49

510
export default Cache
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { NextResponse, NextRequest } from 'next/server'
2+
import { revalidatePath } from 'next/cache'
3+
4+
export const POST = async (req: NextRequest) => {
5+
try {
6+
const { path } = await req.json()
7+
8+
revalidatePath(path)
9+
10+
return NextResponse.json({ message: 'Revalidated' }, { status: 200 })
11+
} catch (err) {
12+
return NextResponse.json({ error: (err as Error).message }, { status: 500 })
13+
}
14+
}

examples/page-router/cacheHandler.mjs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { Cache, FileSystemCache } from '@dbbs/next-cache-handler-core'
22

3-
Cache.addCookies(['abtest']).addQueries(['abtest']).setCacheStrategy(new FileSystemCache()).addDeviceSplit()
3+
Cache.setConfig({
4+
enableDeviceSplit: true,
5+
cacheCookies: ['abtest'],
6+
cacheQueries: ['abtest'],
7+
cache: new FileSystemCache()
8+
})
49

510
export default Cache

0 commit comments

Comments
 (0)