feat: Add new Redis caching to queries

This commit is contained in:
Jesse Wierzbinski 2023-12-01 13:00:00 -10:00
parent df5e8f744b
commit a17b52b2c5
No known key found for this signature in database
7 changed files with 118 additions and 4 deletions

View file

@ -16,6 +16,13 @@ export interface ConfigType {
password: string;
database: number | null;
};
cache: {
host: string;
port: number;
password: string;
database: number | null;
enabled: boolean;
};
};
http: {
@ -159,7 +166,14 @@ export const configDefaults: ConfigType = {
host: "localhost",
port: 6379,
password: "",
database: null,
database: 0,
},
cache: {
host: "localhost",
port: 6379,
password: "",
database: 1,
enabled: false,
},
},
instance: {

60
utils/redis.ts Normal file
View file

@ -0,0 +1,60 @@
import { getConfig } from "@config";
import type { Prisma } from "@prisma/client";
import chalk from "chalk";
import Redis from "ioredis";
import { createPrismaRedisCache } from "prisma-redis-middleware";
const config = getConfig();
const cacheRedis = config.redis.cache.enabled
? new Redis({
host: config.redis.cache.host,
port: Number(config.redis.cache.port),
password: config.redis.cache.password,
db: Number(config.redis.cache.database ?? 0),
})
: null;
cacheRedis?.on("error", e => {
console.log(e);
});
export { cacheRedis };
export const initializeRedisCache = async () => {
if (cacheRedis) {
// Test connection
try {
await cacheRedis.ping();
} catch (e) {
console.error(
`${chalk.red(``)} ${chalk.bold(
`Error while connecting to Redis`
)}`
);
throw e;
}
console.log(`${chalk.green(``)} ${chalk.bold(`Connected to Redis`)}`);
const cacheMiddleware: Prisma.Middleware = createPrismaRedisCache({
storage: {
type: "redis",
options: {
client: cacheRedis,
invalidation: {
referencesTTL: 300,
},
},
},
cacheTime: 300,
onError: e => {
console.error(e);
},
});
return cacheMiddleware;
}
return null;
};