feat: allow associating an existing device ID and token with a username

This commit is contained in:
2024-06-16 08:24:28 -04:00
parent e8aebac6d4
commit f9d7a6bbd2
4 changed files with 112 additions and 7 deletions

View File

@@ -1,4 +1,4 @@
import { eq, sql } from "drizzle-orm";
import { eq, or, sql } from "drizzle-orm";
import type { Env } from "~/types/env";
@@ -10,6 +10,42 @@ export function saveToken(
deviceId: string,
token: string,
username: string | null,
) {
return getDb(env)
.select()
.from(deviceTokensTable)
.where(
or(
eq(deviceTokensTable.deviceId, deviceId),
eq(deviceTokensTable.token, token),
),
)
.then((existingTokens) => {
const existingToken = existingTokens.find(
({ token: existingToken, deviceId: existingDeviceId }) =>
existingToken === token || existingDeviceId === deviceId,
);
if (!existingToken) {
return insertToken(env, deviceId, token, username);
}
if (
existingToken.token === token &&
!existingToken.username &&
!username
) {
throw new Error("Token already exists in the database");
}
return updateToken(env, deviceId, token, username);
});
}
function insertToken(
env: Env,
deviceId: string,
token: string,
username: string | null,
) {
return getDb(env)
.insert(deviceTokensTable)
@@ -17,6 +53,19 @@ export function saveToken(
.run();
}
function updateToken(
env: Env,
deviceId: string,
token: string,
username: string | null,
) {
return getDb(env)
.update(deviceTokensTable)
.set({ token, username })
.where(eq(deviceTokensTable.deviceId, deviceId))
.run();
}
export function updateDeviceLastConnectedAt(env: Env, deviceId: string) {
return getDb(env)
.update(deviceTokensTable)