Что я сделал:
[*] Создал клиент Redis в lib /redis.js < /code> и использовал его внутри пользовательского обработчика кэша. < /li>
Настройка обработчик кэша в next.config.js .
[*] Использование TypeScript в моем проекте (tsconfig.json представлен ниже).
[*] Первоначально создал lib/cache-handler.ts , но это не было признано, поэтому я переместил его в .js Файл. < /li>
< /ol>
Проблемы, с которыми я сталкиваюсь: < /p>
Типография не распознает cache-handler.ts .
[*] Ошибки, связанные с next.config.js (неверные параметры).
неправильная конфигурация в tsconfig.json влияет на сборку.lib/redis.js (redis client):
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
export default redis;
< /code>
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"types": ["io-ts"],
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
},
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true
},
"include": ["**/*.ts", "**/*.tsx", "next-env.d.ts", ".next/types/**/*.ts", "lib/cache-handler.js", "lib/redis.js"],
"exclude": ["node_modules"],
"noUnusedLocals": true,
"noUnusedParameters": true
}
< /code>
This is my custom handler in lib/cache-handler.js (перенесено из .ts на .js из-за проблем распознавания) const getRedisInstance = require('./redis');
class CacheHandler {
constructor(options = { ttl: 3600 }) {
if (!CacheHandler.instance) { // Ensure only one instance is created
this.options = options;
console.log("CacheHandler initialized!");
this.redis = getRedisInstance(); // Use the Redis instance
CacheHandler.instance = this;
}
return CacheHandler.instance;
}
async get(key) {
const cachedData = await this.redis.get(key);
return cachedData ? JSON.parse(cachedData) : null;
}
async set(key, data, ctx = {}) {
const cacheEntry = {
value: data,
lastModified: Date.now(),
tags: ctx.tags || [],
};
await this.redis.set(key, JSON.stringify(cacheEntry), 'EX', this.options.ttl);
if (ctx.tags) {
for (const tag of ctx.tags) {
await this.redis.sadd(`tag:${tag}`, key);
}
}
}
async revalidateTag(tags) {
tags = Array.isArray(tags) ? tags : [tags];
for (const tag of tags) {
const keys = await this.redis.smembers(`tag:${tag}`);
if (keys.length) {
await this.redis.del(...keys);
await this.redis.del(`tag:${tag}`);
}
}
}
resetRequestCache() {}
}
//
const cacheInstance = new CacheHandler();
module.exports = cacheInstance;
< /code>
This is my next.config файл:
/**
* @format
* @type {import('next').NextConfig}
*/
const path = require("path");
const nextConfig = {
logging: {
logging: 'verbose',
fetches: {
fullUrl: true,
},
},
eslint: {
dirs: ['src'],
},
cacheHandler: path.resolve(__dirname, "lib/cache-handler.js"),
cacheMaxMemorySize: 0, // disable default in-memory caching
< /code>
When I run the project I'm getting several errors:
[TypeError: CurCacheHandler is not a constructor]
[TypeError: CurCacheHandler is not a constructor]
[TypeError: CurCacheHandler is not a constructor]
[TypeError: CurCacheHandler is not a constructor]
[TypeError: CurCacheHandler is not a constructor]
[TypeError: CurCacheHandler is not a constructor]
Подробнее здесь: https://stackoverflow.com/questions/794 ... he-handler
Мобильная версия