【问题标题】:AnyCable : Retrieve information gRPC info on ROR AppAnyCable : 在 ROR App 上检索信息 gRPC 信息
【发布时间】:2020-09-04 01:13:07
【问题描述】:

我正在努力将 Action Cable 切换到 AnyCable。

我不使用 cookie 来识别用户,我使用 JWT 因为我的应用只提供 API。

所以在聊天的情况下,我们需要检索发送消息的用户。

在日志中,我看到这条消息1:

RPC Command: <AnyCable::CommandMessage: command: "subscribe", identifier: "{\"channel\":\"RoomChannel\",\"room_id\":\"566\"}", connection_identifiers: "{\"current_user\":{\"id\":\"XXXXXXXX\",\"login_time\":1589745276,\"okta_id\":\"xxxxx@gmail.com\"

如何检索对象“connection_identifiers”的值?

在当前连接类下面: `类:模块ApplicationCable 类连接

identified_by :current_user

def connect
  self.current_user = create_user_from_tokens

  reject_unauthorized_connection unless current_user.valid
end

结束 结束`

create_user_from_tokens > 从 JWT 令牌创建用户对象

以及当前接收新消息的方法: `def接收(内容) 除非接收参数返回 false 除非对话,否则返回 false

message = content['content']

message_params = {conversation_id: @conversation.id,
                  conversation: @conversation,
                  sender_id: @connection.current_user.okta_id,
                  sender_name: @connection.current_user.name,
                  content: message}

ConversationMessageService.post message_params

救援标准错误 Rails.logger.error I18n.t('log.api.websocket.error_receive') 渲染 json: {错误: :bad_request, error_description: I18n.t('log.api.websocket.error_receive'), error_uri: ''}, 状态: :bad_request 结束`

据我所知,无法检索@connection。

【问题讨论】:

  • 能否提供您的连接类代码?另外,您能否提供一个您想要检索用户的示例频道代码?
  • @palkan,我已经用代码示例编辑了帖子。

标签: ruby-on-rails actioncable


【解决方案1】:

要从频道访问当前用户,您可以使用#current_user 访问器(Rails 会自动为您添加此委托)。

所以,代码应该是:

message_params = {conversation_id: @conversation.id,
                  conversation: @conversation,
                  sender_id: current_user.okta_id,
                  sender_name: current_user.name,
                  content: message}

如果我理解正确的话,你的 current_user 对象不是 AR 记录,而是一个普通的 Ruby 类,对吧?

那么current_user 在频道中只会返回一个 JSON 编码的字符串,而不是对象。

目前,AnyCable 使用 GlobalID 来序列化/反序列化连接标识符。您必须将 GlobalID 功能添加到您的类,以使其与 AnyCable 的工作方式与 Action Cable 的工作方式相同。例如:

class User
  include GlobalID::Identification

  def self.find_by_gid(gid)
    new(gid.params)
  end

  def to_global_id
    super(to_h.merge!(app: :custom))
  end

  alias to_gid to_global_id
end

# setup GlobalID to correctly resolve your custom class
GlobalID::Locator.use :custom do |gid|
  gid.model_name.constantize.find_by_gid(gid)
end

【讨论】:

  • 谢谢,我使用了 current_user 的解决方案,效果很好,这两种解决方案之一是更好或更有效吗?
  • 我不认为有显着的性能差异,所以由你决定哪一个更适合你的代码库
猜你喜欢
  • 2012-02-05
  • 2023-03-07
  • 2011-01-13
  • 2013-08-08
  • 2011-12-10
  • 2017-06-19
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多