60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
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] | null,
|
|
) {
|
|
let dbAction;
|
|
const isSavingTitle = watchStatus === "CURRENT" || watchStatus === "PLANNING";
|
|
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),
|
|
),
|
|
);
|
|
}
|