Rails 5 API + 实时通知

Rails 5 API + Real time notifications

我正在创建一个 Rails 5 API,我需要创建一个实时网络通知。

使用 ActionCable 可以吗?有没有人有 Action Cable 或任何其他解决方案的示例?

提前致谢。

这是一个网络通知渠道,允许您在向正确的流广播时触发客户端网络通知:

创建服务器端网络通知通道:

# app/channels/web_notifications_channel.rb
class WebNotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_for current_user
  end
end

创建客户端网络通知频道订阅:

# app/assets/javascripts/cable/subscriptions/web_notifications.coffee
# Client-side which assumes you've already requested
# the right to send web notifications.
App.cable.subscriptions.create "WebNotificationsChannel",
  received: (data) ->
    new Notification data["title"], body: data["body"]

将内容从应用程序中的其他地方广播到网络通知通道实例:

# Somewhere in your app this is called, perhaps from a NewCommentJob
WebNotificationsChannel.broadcast_to(
  current_user,
  title: 'New things!',
  body: 'All the news fit to print'
)

WebNotificationsChannel.broadcast_to 调用在当前订阅适配器的 pubsub 队列中为每个用户在单独的广播名称下放置一条消息。对于 ID 为 1 的用户,广播名称将为 web_notifications:1.