mirror of
https://github.com/versia-pub/server.git
synced 2026-03-13 05:49:16 +01:00
feat: Add new Redis caching to queries
This commit is contained in:
parent
df5e8f744b
commit
a17b52b2c5
7 changed files with 118 additions and 4 deletions
|
|
@ -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
60
utils/redis.ts
Normal 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;
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue