AnyCable:在 ROR App 上检索信息 gRPC 信息

AnyCable : Retrieve information gRPC info on ROR App

我正在努力将 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"?

当前连接下方Class: `Class:模块ApplicationCable class 连接 < ActionCable::Connection::Base 包括身份验证

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 接收(内容) return 假除非 receive_params return 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。

要从频道访问当前用户,您可以使用 #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 class,对吧?

然后 current_user 在通道中将只是 return 一个 JSON 编码的字符串,而不是对象。

目前,AnyCable 使用 GlobalID 来 serialize/deserialize 连接标识符。您必须将 GlobalID 功能添加到您的 class 以使其与 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