From 7544049e95babc277ab8f6d4106392b3e714648c Mon Sep 17 00:00:00 2001 From: Arseny <132773930+better-salmon@users.noreply.github.com> Date: Fri, 17 Nov 2023 05:50:12 +0300 Subject: [PATCH] Update `cache-handler-redis` example --- examples/cache-handler-redis/README.md | 2 + .../cache-handler-redis-custom.js | 103 ++++++++++++++++++ .../cache-handler-redis-stack.js | 98 ----------------- .../cache-handler-redis.js | 88 ++------------- examples/cache-handler-redis/next.config.js | 4 +- examples/cache-handler-redis/package.json | 2 +- 6 files changed, 120 insertions(+), 177 deletions(-) create mode 100644 examples/cache-handler-redis/cache-handler-redis-custom.js delete mode 100644 examples/cache-handler-redis/cache-handler-redis-stack.js diff --git a/examples/cache-handler-redis/README.md b/examples/cache-handler-redis/README.md index b541892b6349b..7e03e31efe563 100644 --- a/examples/cache-handler-redis/README.md +++ b/examples/cache-handler-redis/README.md @@ -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/). diff --git a/examples/cache-handler-redis/cache-handler-redis-custom.js b/examples/cache-handler-redis/cache-handler-redis-custom.js new file mode 100644 index 0000000000000..811861edd08d9 --- /dev/null +++ b/examples/cache-handler-redis/cache-handler-redis-custom.js @@ -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 diff --git a/examples/cache-handler-redis/cache-handler-redis-stack.js b/examples/cache-handler-redis/cache-handler-redis-stack.js deleted file mode 100644 index 6390f16cd6f45..0000000000000 --- a/examples/cache-handler-redis/cache-handler-redis-stack.js +++ /dev/null @@ -1,98 +0,0 @@ -const { IncrementalCache } = require('@neshca/cache-handler') -const { createClient } = require('redis') - -/** @type {import('@neshca/cache-handler').TagsManifest} */ -let 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 connectAndSetManifest(client) { - try { - await client.connect() - } catch (error) { - console.error('Redis connection error:', error.message) - } - - try { - await client.json.set(TAGS_MANIFEST_KEY, '.', localTagsManifest, { - NX: true, - }) - } catch (error) { - console.error('Redis set tagsManifest error:', error.message) - } -} - -const client = createRedisClient( - process.env.REDIS_URL ?? 'redis://localhost:6379' -) - -connectAndSetManifest(client).then(() => { - console.log('Redis connected') -}) - -IncrementalCache.onCreation(() => { - return { - cache: { - async get(key) { - try { - const value = (await client.json.get(key)) ?? null - - if (value && value.kind === 'ROUTE' && value.body.type === 'Buffer') { - value.body = Buffer.from(value.body) - } - - return value - } catch (error) { - return null - } - }, - async set(key, value) { - try { - await client.json.set(key, '.', value) - } catch (error) { - // ignore because value will be written to disk - } - }, - async getTagsManifest() { - try { - const sharedTagsManifest = - (await client.json.get(TAGS_MANIFEST_KEY)) ?? null - - if (sharedTagsManifest) { - localTagsManifest = sharedTagsManifest - } - - return sharedTagsManifest - } catch (error) { - return localTagsManifest - } - }, - async revalidateTag(tag, revalidatedAt) { - try { - await client.json.set(TAGS_MANIFEST_KEY, `.items.${tag}`, { - revalidatedAt, - }) - } catch (error) { - localTagsManifest.items[tag] = { revalidatedAt } - } - }, - }, - } -}) - -module.exports = IncrementalCache diff --git a/examples/cache-handler-redis/cache-handler-redis.js b/examples/cache-handler-redis/cache-handler-redis.js index 811861edd08d9..5d229252b4604 100644 --- a/examples/cache-handler-redis/cache-handler-redis.js +++ b/examples/cache-handler-redis/cache-handler-redis.js @@ -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, @@ -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 diff --git a/examples/cache-handler-redis/next.config.js b/examples/cache-handler-redis/next.config.js index 3f3b96974cb4a..261e0448d260b 100644 --- a/examples/cache-handler-redis/next.config.js +++ b/examples/cache-handler-redis/next.config.js @@ -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, }, diff --git a/examples/cache-handler-redis/package.json b/examples/cache-handler-redis/package.json index 1443815ff8ad7..e5369cbcd121f 100644 --- a/examples/cache-handler-redis/package.json +++ b/examples/cache-handler-redis/package.json @@ -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",