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

@@ -195,6 +195,64 @@ describe("requests the /token route", () => {
expect(row).toBeUndefined();
});
it("associating a username with a token, should succeed", async () => {
await db
.insert(deviceTokensTable)
.values({ deviceId: "123", token: "123" });
const res = await app.request("/token", {
method: "POST",
headers: new Headers({
"Content-Type": "application/json",
}),
body: JSON.stringify({
token: "123",
deviceId: "123",
username: "aniplay",
}),
});
expect(res.json()).resolves.toEqual({ success: true });
expect(res.status).toBe(200);
});
it("associating a username with a token should update existing entry", async () => {
const minimumTimestamp = DateTime.now();
await db
.insert(deviceTokensTable)
.values({ deviceId: "123", token: "123" });
await app.request("/token", {
method: "POST",
headers: new Headers({
"Content-Type": "application/json",
}),
body: JSON.stringify({
token: "123",
deviceId: "123",
username: "aniplay",
}),
});
const row = await db
.select()
.from(deviceTokensTable)
.where(eq(deviceTokensTable.deviceId, "123"))
.get();
expect(row).toEqual({
deviceId: "123",
token: "123",
username: "aniplay",
lastConnectedAt: expect.any(String),
});
// since SQL timestamp doesn't support milliseconds, compare to nearest second
expect(
+DateTime.fromSQL(row!.lastConnectedAt!, { zone: "utc" }).startOf(
"second",
),
).toBeGreaterThanOrEqual(+minimumTimestamp.startOf("second"));
});
it("token is invalid, should fail", async () => {
mock.module("src/libs/fcm/verifyFcmToken", () => ({
verifyFcmToken: () => false,

View File

@@ -69,11 +69,7 @@ app.openapi(route, async (c) => {
await saveToken(env(c, "workerd"), deviceId, token, username);
} catch (error) {
// when token already exists in the database
if (
error.code === "SQLITE_CONSTRAINT" &&
error.message.includes("device_tokens.token")
) {
if (error.message === "Token already exists in the database") {
return c.json(ErrorResponse, 412);
}