feat: set up Drizzle

This commit is contained in:
2024-06-12 09:29:58 -04:00
parent 5843dfdeb2
commit 06bb8f65fb
13 changed files with 403 additions and 5 deletions

59
src/models/watchStatus.ts Normal file
View File

@@ -0,0 +1,59 @@
import { and, count, eq } from "drizzle-orm";
import type { Env } from "~/types/env";
import { WatchStatusValues } from "~/types/title/watchStatus";
import { getDb } from "./db";
import { watchStatusTable } from "./schema";
/** If watch status is "CURRENT", the title will be added to the watch status table. Otherwise, it will be removed.
*
* @returns an object with the following properties:
* - wasAdded: whether the title was set as watching for the first time
* - wasDeleted: whether any users are still watching the title
*/
export function setWatchStatus(
env: Env,
deviceId: string,
titleId: number,
watchStatus: (typeof WatchStatusValues)[number],
) {
let dbAction;
const isSavingTitle = watchStatus === "CURRENT";
if (isSavingTitle) {
dbAction = saveTitle(env, deviceId, titleId);
} else {
dbAction = removeTitle(env, deviceId, titleId);
}
return dbAction
.then(() =>
getDb(env)
.select({ count: count(watchStatusTable.titleId) })
.from(watchStatusTable)
.where(eq(watchStatusTable.titleId, titleId))
.get(),
)
.then((result) => ({
wasAdded: isSavingTitle && result?.count === 1,
wasDeleted: !isSavingTitle && result?.count === 0,
}));
}
function saveTitle(env: Env, deviceId: string, titleId: number) {
return getDb(env)
.insert(watchStatusTable)
.values({ deviceId, titleId })
.onConflictDoNothing();
}
function removeTitle(env: Env, deviceId: string, titleId: number) {
return getDb(env)
.delete(watchStatusTable)
.where(
and(
eq(watchStatusTable.deviceId, deviceId),
eq(watchStatusTable.titleId, titleId),
),
);
}