所以,我所做的是将notification_subscription 模型添加到我的User 模型中。
在我的 javascript 上,我检查是否存在当前的浏览器订阅:
this.serviceWorkerReady()
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((pushSubscription) => {
if (pushSubscription && _.includes(subscriptionEndpoints, pushSubscription.endpoint)) {
return;
}
this.subscribe();
});
});
我检查当前订阅是否已经存在于用户存储的端点中,如果不存在则订阅。
在订阅时,我将新端点发送到后端,这会将新订阅添加到用户:
$.post(Routes.users_subscriptions_path({ format: 'json' }), {
subscription: subscription.toJSON()
});
然后我可以向每个端点的用户发送通知:
def push_notifications_to_user(user)
message = {
title: "A message!",
tag: 'notification-tag'
}
user.notification_subscriptions.each do |subscription|
begin
Webpush.payload_send(
message: JSON.generate(message),
endpoint: endpoint,
p256dh: p256dh,
auth: auth,
api_key: public_key
)
rescue Webpush::InvalidSubscription => exception
subscription.destroy
end
end
end
如果端点无效,webpush gem 会引发 InvalidSubscription 异常,我们可以销毁该端点以仅保留用户的有效端点。