46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
import { and, eq, gt, isNull, or } from "drizzle-orm";
|
|
import { danmakuCache, type DanmakuCacheRow } from "@app/models";
|
|
import { db } from "@app/db";
|
|
|
|
export const danmakuCacheDao = {
|
|
async getValid(matchKey: string): Promise<DanmakuCacheRow | null> {
|
|
const now = new Date();
|
|
const [row] = await db
|
|
.select()
|
|
.from(danmakuCache)
|
|
.where(
|
|
and(
|
|
eq(danmakuCache.matchKey, matchKey),
|
|
or(isNull(danmakuCache.expiresAt), gt(danmakuCache.expiresAt, now)),
|
|
),
|
|
)
|
|
.limit(1);
|
|
return row ?? null;
|
|
},
|
|
async upsert(data: {
|
|
matchKey: string;
|
|
payload: string;
|
|
source: string;
|
|
expiresAt: Date | null;
|
|
}): Promise<DanmakuCacheRow> {
|
|
const existing = await db
|
|
.select()
|
|
.from(danmakuCache)
|
|
.where(eq(danmakuCache.matchKey, data.matchKey))
|
|
.limit(1);
|
|
if (existing[0]) {
|
|
const [row] = await db
|
|
.update(danmakuCache)
|
|
.set({ payload: data.payload, source: data.source, expiresAt: data.expiresAt })
|
|
.where(eq(danmakuCache.id, existing[0].id))
|
|
.returning();
|
|
if (!row) throw new Error("Failed to update danmaku cache");
|
|
return row;
|
|
}
|
|
const rows = await db.insert(danmakuCache).values(data).returning();
|
|
const row = rows[0];
|
|
if (!row) throw new Error("Failed to insert danmaku cache");
|
|
return row;
|
|
},
|
|
};
|