feat: allow associating an existing device ID and token with a username
This commit is contained in:
@@ -11,7 +11,9 @@ export const deviceTokensTable = sqliteTable("device_tokens", {
|
||||
token: text("token").notNull().unique(),
|
||||
username: text("username"),
|
||||
/** Used to determine if a device hasn't been used in a while. Should start to ignore tokens where the device hasn't connected in about a month. */
|
||||
lastConnectedAt: text("last_connected_at").default(sql`(CURRENT_TIMESTAMP)`),
|
||||
lastConnectedAt: text("last_connected_at")
|
||||
.default(sql`(CURRENT_TIMESTAMP)`)
|
||||
.$onUpdate(() => sql`(CURRENT_TIMESTAMP)`),
|
||||
});
|
||||
|
||||
export const watchStatusTable = sqliteTable(
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user