检测多个过期的 Firebase 云消息令牌
Detect multiple expired Firebase Cloud Messaging Tokens
我知道我可以知道令牌是否已过期,如 Google 文档中所述:
https://developers.google.com/instance-id/reference/server#get_information_about_app_instances
问题是我有数百个令牌,我想每周都知道其中是否有过期的。为每个令牌发送请求并不是很好。无论如何发送一个带有这些令牌数组或类似内容的单个请求?谢谢!
处理过期令牌的常用方法是在您尝试向它们发送消息时收到 "token expired" 响应时将其删除。由于您可以一次向多个令牌发送消息,因此无需为每个令牌执行单独的调用。
有关如何执行此操作的一个很好的示例,请参阅此 snippet from the Cloud Functions example of using FCM through the Admin SDK:
// Listing all tokens as an array.
tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
我知道我可以知道令牌是否已过期,如 Google 文档中所述:
https://developers.google.com/instance-id/reference/server#get_information_about_app_instances
问题是我有数百个令牌,我想每周都知道其中是否有过期的。为每个令牌发送请求并不是很好。无论如何发送一个带有这些令牌数组或类似内容的单个请求?谢谢!
处理过期令牌的常用方法是在您尝试向它们发送消息时收到 "token expired" 响应时将其删除。由于您可以一次向多个令牌发送消息,因此无需为每个令牌执行单独的调用。
有关如何执行此操作的一个很好的示例,请参阅此 snippet from the Cloud Functions example of using FCM through the Admin SDK:
// Listing all tokens as an array. tokens = Object.keys(tokensSnapshot.val()); // Send notifications to all tokens. const response = await admin.messaging().sendToDevice(tokens, payload); // For each message check if there was an error. const tokensToRemove = []; response.results.forEach((result, index) => { const error = result.error; if (error) { console.error('Failure sending notification to', tokens[index], error); // Cleanup the tokens who are not registered anymore. if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') { tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove()); } } }); return Promise.all(tokensToRemove);