feat(notifications): persist stable deviceId for FCM registration

Add getOrCreateDeviceId() backed by Capacitor Preferences so one UUID
survives app restarts and token refreshes. Include deviceId in POST
/notifications/register alongside fcmToken, platform, and testMode.
Add @capacitor/preferences and lightweight DeviceId logs (no token/ID values).
This commit is contained in:
Jose Olarte III
2026-05-13 18:41:10 +08:00
parent 5a40075ab1
commit 6a9f34a516
4 changed files with 959 additions and 284 deletions

1210
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -148,6 +148,7 @@
"@capacitor/core": "^6.2.0",
"@capacitor/filesystem": "^6.0.0",
"@capacitor/ios": "^6.2.0",
"@capacitor/preferences": "^6.0.4",
"@capacitor/push-notifications": "^6.0.5",
"@capacitor/share": "^6.0.3",
"@capacitor/status-bar": "^6.0.2",

View File

@@ -15,6 +15,7 @@
import { Capacitor } from "@capacitor/core";
import { logger } from "@/utils/logger";
import { getOrCreateDeviceId } from "./deviceId";
import { NativeNotificationService } from "./NativeNotificationService";
import { WebPushNotificationService } from "./WebPushNotificationService";
@@ -22,10 +23,12 @@ import { WebPushNotificationService } from "./WebPushNotificationService";
* Registers an FCM device token with the app backend (native Capacitor token or web getToken).
*/
export async function registerToken(fcmToken: string): Promise<void> {
const deviceId = await getOrCreateDeviceId();
const res = await fetch("/notifications/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
deviceId,
fcmToken,
platform: Capacitor.getPlatform(),
testMode: true,

View File

@@ -0,0 +1,29 @@
import { Preferences } from "@capacitor/preferences";
const DEVICE_ID_KEY = "stable_device_id";
function generateDeviceId(): string {
return crypto.randomUUID();
}
export async function getOrCreateDeviceId(): Promise<string> {
const existing = await Preferences.get({ key: DEVICE_ID_KEY });
if (existing.value) {
// eslint-disable-next-line no-console
console.log("[DeviceId] Loaded existing deviceId");
return existing.value;
}
const newId = generateDeviceId();
await Preferences.set({
key: DEVICE_ID_KEY,
value: newId,
});
// eslint-disable-next-line no-console
console.log("[DeviceId] Generated new deviceId");
return newId;
}