Skip to content

Commit 6c028bf

Browse files
Fix FCM cleanup logic
1 parent e5593ce commit 6c028bf

File tree

2 files changed

+21
-13
lines changed
  • Node/fcm-notifications/functions
  • Python/fcm-notifications/functions

2 files changed

+21
-13
lines changed

Node/fcm-notifications/functions/index.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -83,12 +83,16 @@ export const sendFollowerNotification = onValueWritten(
8383
batchResponse);
8484

8585
// Clean up the tokens that are not registered any more.
86-
for (const response of batchResponse.responses) {
87-
if (response.error?.code ===
88-
"messaging/invalid-registration-token" ||
89-
response.error?.code ===
90-
"messaging/registration-token-not-registered") {
91-
await tokensRef.child(response.messageId).remove();
86+
for (let i = 0; i < batchResponse.responses.length; i++) {
87+
const errorCode = batchResponse.responses[i].error?.code;
88+
const errorMessage = batchResponse.responses[i].error?.message;
89+
if ((errorCode === "messaging/invalid-registration-token") ||
90+
(errorCode === "messaging/registration-token-not-registered") ||
91+
(errorCode === "messaging/invalid-argument" &&
92+
errorMessage ===
93+
"The registration token is not a valid FCM registration token")) {
94+
log(`Removing invalid token: ${messages[i].token}`);
95+
await tokensRef.child(messages[i].token).remove();
9296
}
9397
}
9498
});

Python/fcm-notifications/functions/main.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import firebase_admin
2-
from firebase_admin import auth, db, messaging
2+
from firebase_admin import auth, db, messaging, exceptions
33
from firebase_functions import db_fn
44

55
firebase_admin.initialize_app()
6+
messaging.UnregisteredError
67

78

89
@db_fn.on_value_written(reference=r"followers/{followedUid}/{followerUid}")
@@ -45,10 +46,13 @@ def send_follower_notification(event: db_fn.Event[db_fn.Change]) -> None:
4546
if batch_response.failure_count < 1:
4647
# Messages sent sucessfully. We're done!
4748
return
49+
4850
# Clean up the tokens that are not registered any more.
49-
for response in batch_response.responses:
50-
if response.exception.code in (
51-
"messaging/invalid-registration-token",
52-
"messaging/registration-token-not-registered",
53-
):
54-
tokens_ref.child(response.message_id).delete()
51+
for i in range(len(batch_response.responses)):
52+
exception = batch_response.responses[i].exception
53+
if not isinstance(exception, exceptions.FirebaseError):
54+
continue
55+
message = exception.http_response.json()["error"]["message"]
56+
if (isinstance(exception, messaging.UnregisteredError) or
57+
message == "The registration token is not a valid FCM registration token"):
58+
tokens_ref.child(msgs[i].token).delete()

0 commit comments

Comments
 (0)