我正在使用 Firebase 云功能发送用户推送通知。我不太了解 JS,但我希望能够通过通知有效负载自动增加应用程序徽章编号,并为收到的每个通知将数字增加 1。这就是我现在所拥有的。我已经阅读了 firebase 的文档,但我认为我没有足够的 JS 理解来弄清楚他们所描述的内容。

exports.sendPushNotificationLikes = functions.database.ref('/friend-like-push-notifications/{userId}/{postId}/{likerId}').onWrite(event => { 
const userUid = event.params.userId; 
const postUid = event.params.postId; 
const likerUid = event.params.likerId; 
if (!event.data.val()) { 
    return; 
} 
 
// const likerProfile = admin.database().ref(`/users/${likerUid}/profile/`).once('value'); 
 
const getDeviceTokensPromise = admin.database().ref(`/users/${userUid}/fcmToken`).once('value'); 
 
// Get the follower profile. 
const getLikerProfilePromise = admin.auth().getUser(likerUid); 
 
return Promise.all([getDeviceTokensPromise, getLikerProfilePromise]).then(results => { 
    const tokensSnapshot = results[0]; 
    const user = results[1]; 
 
    if (!tokensSnapshot.hasChildren()) { 
        return console.log('There are no notification tokens to send to.'); 
    } 
 
    const payload = { 
        notification: { 
            title: 'New Like!', 
            body: '${user.username} liked your post!', 
            sound: 'default', 
            badge: += 1.toString() 
       } 
    }; 
 
    const tokens = Object.keys(tokensSnapshot.val()); 
 
    // Send notifications to all tokens. 
    return admin.messaging().sendToDevice(tokens, payload).then(response => { 
            // 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); 
    }); 
}); 

});

预先感谢您的帮助

请您参考如下方法:

我猜这就是问题所在:

const payload = { 
   notification: { 
       title: 'New Like!', 
       body: '${user.username} liked your post!', 
       sound: 'default', 
       badge: += 1.toString() 
   } 
}; 

假设您的架构中有一个可用的通知计数属性,例如 notificationCount,那么您可以执行以下操作:

const payload = { 
   notification: { 
       title: 'New Like!', 
       body: `${user.username} liked your post!`, 
       sound: 'default', 
       badge: Number(notificationCount++) // => notificationCount + 1 
   } 
}; 

此外,在此正文中:“${user.username} 喜欢您的帖子!”,这将保存为“user.username like your post!”。这不是您想要的行为,您应该做的是:

body: `${user.username} liked your post!` 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!