From e701dd798bbb30c3c3c2c1c4b9d526d462ef0834 Mon Sep 17 00:00:00 2001 From: Xevion Date: Sat, 25 Feb 2023 03:14:48 -0600 Subject: [PATCH] Redis configuration fetching, parsing, set/get methods --- src/db.ts | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/src/db.ts b/src/db.ts index a756b50..4c24fe5 100644 --- a/src/db.ts +++ b/src/db.ts @@ -1,14 +1,40 @@ +import { Configuration, ConfigurationSchema } from './timing'; import { Redis } from 'ioredis'; import { env } from '@/env/server.mjs'; import { format } from 'date-fns'; -console.log(env.REDIS_URL); const redis = new Redis(env.REDIS_URL, { maxRetriesPerRequest: 2 }); -export async function test() { - const now = new Date(); - const key = format(now, 'yyyy-MM-dd'); - - const current = await redis.incr(key); - return current; +export async function fetchConfiguration( + defaultConfig?: object +): Promise { + const config = await redis.get('config'); + if (config == null) + if (defaultConfig != undefined) + return ConfigurationSchema.parse(defaultConfig); + else throw new Error('Configuration not found in Redis'); + return ConfigurationSchema.parse(JSON.parse(config)); +} + +export function getKey(identifier: string, now: Date) { + return format(now, 'yyyy-MM-dd') + ':' + identifier; +} + +export async function checkIdentifier( + identifier: string, + now: Date = new Date() +): Promise { + const key = getKey(identifier, now); + return (await redis.get(key)) === '1'; +} + +export async function markIdentifier( + identifier: string, + value: boolean = true, + expiry?: number, + now: Date = new Date() +) { + const key = getKey(identifier, now); + if (expiry == undefined) return await redis.set(key, value ? '1' : '0'); + return await redis.set(key, value ? '1' : '0', 'EX', expiry); }