oneuptime/CommonServer/Infrastructure/GlobalCache.ts

84 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-12-16 14:50:44 +00:00
import { JSONObject } from 'Common/Types/JSON';
import JSONFunctions from 'Common/Types/JSONFunctions';
2022-07-14 21:38:27 +00:00
import Redis, { ClientType } from './Redis';
import DatabaseNotConnectedException from 'Common/Types/Exception/DatabaseNotConnectedException';
import OneUptimeDate from 'Common/Types/Date';
import logger from '../Utils/Logger';
2022-04-07 14:11:34 +00:00
2022-07-14 17:00:57 +00:00
export default abstract class Cache {
2022-07-14 21:38:27 +00:00
public static async getJSON(
namespace: string,
key: string
): Promise<JSONObject | null> {
2022-07-15 13:49:56 +00:00
const value: string | null = await this.getString(namespace, key);
2022-07-14 21:25:26 +00:00
if (!value) {
return null;
}
2022-07-14 17:00:57 +00:00
2022-07-14 21:25:26 +00:00
try {
2022-07-18 14:22:40 +00:00
const jsonObject: JSONObject = JSONFunctions.deserialize(
2023-05-08 13:22:16 +00:00
JSONFunctions.parse(value)
2022-07-18 14:22:40 +00:00
) as JSONObject;
2022-07-14 17:00:57 +00:00
2022-07-14 21:25:26 +00:00
if (!jsonObject) {
return null;
}
2022-07-14 21:38:27 +00:00
return jsonObject;
2022-07-14 21:25:26 +00:00
} catch (err) {
logger.error(err);
2022-07-14 17:00:57 +00:00
return null;
}
}
2022-07-15 13:49:56 +00:00
public static async getString(
namespace: string,
key: string
): Promise<string | null> {
const client: ClientType | null = Redis.getClient();
if (!client || !Redis.isConnected()) {
throw new DatabaseNotConnectedException('Cache is not connected');
}
const value: string | null = await client?.get(`${namespace}-${key}`);
if (!value) {
return null;
}
2022-07-18 14:22:40 +00:00
return value;
2022-07-15 13:49:56 +00:00
}
2022-07-14 21:38:27 +00:00
public static async setJSON(
namespace: string,
key: string,
value: JSONObject
2022-07-15 13:49:56 +00:00
): Promise<void> {
2022-07-18 14:22:40 +00:00
await this.setString(
namespace,
key,
JSON.stringify(JSONFunctions.serialize(value))
);
2022-07-15 13:49:56 +00:00
}
public static async setString(
namespace: string,
key: string,
value: string
2022-07-14 21:38:27 +00:00
): Promise<void> {
2022-07-14 17:00:57 +00:00
const client: ClientType | null = Redis.getClient();
if (!client || !Redis.isConnected()) {
2022-07-14 21:38:27 +00:00
throw new DatabaseNotConnectedException('Cache is not connected');
2022-07-14 17:00:57 +00:00
}
2022-07-15 13:49:56 +00:00
await client.set(`${namespace}-${key}`, value);
2022-07-14 21:38:27 +00:00
await client.expire(
`${namespace}-${key}`,
OneUptimeDate.getSecondsInDays(30)
);
2022-07-14 17:00:57 +00:00
}
2022-04-07 14:11:34 +00:00
}