Skip to content

Commit

Permalink
examples: Update cache-handler-redis (#58562)
Browse files Browse the repository at this point in the history
  • Loading branch information
better-salmon authored Nov 17, 2023
1 parent ba3ef55 commit 10c794a
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 177 deletions.
2 changes: 2 additions & 0 deletions examples/cache-handler-redis/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ Then, build and start the Next.js app as usual.

## Notes

- **Handlers:** The `@neshca/cache-handler` package now includes new [Handlers](https://caching-tools.github.io/next-shared-cache/redis-stack) for Redis, making it almost zero-config.

- **Think different:** Ensure that your Redis server is operational and accessible before starting your Next.js application to prevent any connection errors. Remember to flush the cache or use namespacing if you preserve the Redis instance between builds.

- **Configure:** Add your Redis credentials to the provided `cache-handler-redis*` files. Learn more about connecting to Redis with Node.js [here](https://redis.io/docs/connect/clients/nodejs/).
Expand Down
103 changes: 103 additions & 0 deletions examples/cache-handler-redis/cache-handler-redis-custom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
const {
reviveFromBase64Representation,
replaceJsonWithBase64,
} = require('@neshca/json-replacer-reviver')
const { IncrementalCache } = require('@neshca/cache-handler')
const { createClient } = require('redis')

/** @type {import('@neshca/cache-handler').TagsManifest} */
const localTagsManifest = {
version: 1,
items: {},
}

const TAGS_MANIFEST_KEY = 'sharedTagsManifest'

function createRedisClient(url) {
const client = createClient({
url,
})

client.on('error', (error) => {
console.error('Redis error:', error.message)
})

return client
}

async function connect(client) {
try {
await client.connect()
} catch (error) {
console.error('Redis connection error:', error.message)
}
}

IncrementalCache.onCreation(() => {
const client = createRedisClient(
process.env.REDIS_URL ?? 'redis://localhost:6379'
)

connect(client).then(() => {
console.log('Redis connected')
})

return {
cache: {
async get(key) {
try {
const result = (await client.get(key)) ?? null

if (!result) {
return null
}

// use reviveFromBase64Representation to restore binary data from Base64
return JSON.parse(result, reviveFromBase64Representation)
} catch (error) {
return null
}
},
async set(key, value) {
try {
// use replaceJsonWithBase64 to store binary data in Base64 and save space
await client.set(key, JSON.stringify(value, replaceJsonWithBase64))
} catch (error) {
// ignore because value will be written to disk
}
},
async getTagsManifest() {
try {
const remoteTagsManifest = await client.hGetAll(TAGS_MANIFEST_KEY)

if (!remoteTagsManifest) {
return localTagsManifest
}

Object.entries(remoteTagsManifest).reduce(
(acc, [tag, revalidatedAt]) => {
acc[tag] = { revalidatedAt: parseInt(revalidatedAt ?? '0', 10) }
return acc
},
localTagsManifest.items
)

return localTagsManifest
} catch (error) {
return localTagsManifest
}
},
async revalidateTag(tag, revalidatedAt) {
try {
await client.hSet(TAGS_MANIFEST_KEY, {
[tag]: revalidatedAt,
})
} catch (error) {
localTagsManifest.items[tag] = { revalidatedAt }
}
},
},
}
})

module.exports = IncrementalCache
98 changes: 0 additions & 98 deletions examples/cache-handler-redis/cache-handler-redis-stack.js

This file was deleted.

88 changes: 12 additions & 76 deletions examples/cache-handler-redis/cache-handler-redis.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
const {
reviveFromBase64Representation,
replaceJsonWithBase64,
} = require('@neshca/json-replacer-reviver')
const { IncrementalCache } = require('@neshca/cache-handler')
const { createHandler } = require('@neshca/cache-handler/redis-stack') // @neshca/cache-handler/redis-strings also available
const { createClient } = require('redis')

/** @type {import('@neshca/cache-handler').TagsManifest} */
const localTagsManifest = {
version: 1,
items: {},
}

const TAGS_MANIFEST_KEY = 'sharedTagsManifest'

function createRedisClient(url) {
const client = createClient({
url,
Expand All @@ -33,71 +22,18 @@ async function connect(client) {
}
}

IncrementalCache.onCreation(() => {
const client = createRedisClient(
process.env.REDIS_URL ?? 'redis://localhost:6379'
)

connect(client).then(() => {
console.log('Redis connected')
})

return {
cache: {
async get(key) {
try {
const result = (await client.get(key)) ?? null

if (!result) {
return null
}
const client = createRedisClient(
process.env.REDIS_URL ?? 'redis://localhost:6379'
)

// use reviveFromBase64Representation to restore binary data from Base64
return JSON.parse(result, reviveFromBase64Representation)
} catch (error) {
return null
}
},
async set(key, value) {
try {
// use replaceJsonWithBase64 to store binary data in Base64 and save space
await client.set(key, JSON.stringify(value, replaceJsonWithBase64))
} catch (error) {
// ignore because value will be written to disk
}
},
async getTagsManifest() {
try {
const remoteTagsManifest = await client.hGetAll(TAGS_MANIFEST_KEY)

if (!remoteTagsManifest) {
return localTagsManifest
}

Object.entries(remoteTagsManifest).reduce(
(acc, [tag, revalidatedAt]) => {
acc[tag] = { revalidatedAt: parseInt(revalidatedAt ?? '0', 10) }
return acc
},
localTagsManifest.items
)

return localTagsManifest
} catch (error) {
return localTagsManifest
}
},
async revalidateTag(tag, revalidatedAt) {
try {
await client.hSet(TAGS_MANIFEST_KEY, {
[tag]: revalidatedAt,
})
} catch (error) {
localTagsManifest.items[tag] = { revalidatedAt }
}
},
},
}
connect(client).then(() => {
console.log('Redis connected')
})

IncrementalCache.onCreation(
createHandler({
client,
})
)

module.exports = IncrementalCache
4 changes: 2 additions & 2 deletions examples/cache-handler-redis/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const nextConfig = {
incrementalCacheHandlerPath:
process.env.NODE_ENV === 'production'
? require.resolve(
// './cache-handler-redis.js' // if you're using Redis without JSON support
'./cache-handler-redis-stack.js'
// './cache-handler-redis-custom.js' // custom configuration
'./cache-handler-redis.js'
)
: undefined,
},
Expand Down
2 changes: 1 addition & 1 deletion examples/cache-handler-redis/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"devDependencies": {
"@neshca/cache-handler": "latest",
"@neshca/json-replacer-reviver": "latest",
"@types/node": "^20.9.0",
"@types/node": "^20.9.1",
"@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15",
"redis": "latest",
Expand Down

0 comments on commit 10c794a

Please sign in to comment.