ruby-jp / websocket-client-simple

Simple WebSocket Client on Ruby
https://rubygems.org/gems/websocket-client-simple
MIT License
41 stars 6 forks source link

Insert a graphQL susbcription query #19

Open nicohc opened 1 year ago

nicohc commented 1 year ago

Hello, Thanks for your nice gem,

I wondering if it's possible to send a graphQL query with the gem : For the moment , i just receive the welcome and ping message of an external websocket. ref: Here is my code : (I also added a header and subprotocol, but not sure if it's the right way to mention it too)

In my controller :

  require 'websocket-client-simple'
  require 'json'

  url = "wss://ws.sorare.com/cable"
  subprotocol = 'actioncable-v1-json'
  header = {
    "Authorization" => "Bearer #{ENV['S_TKN']}"
  }

  query = <<-GRAPHQL
    subscription {
      aCardWasUpdated { slug }
    }
  GRAPHQL

  data = { 'query' => query, 'variables' => {} }
  message = { 'command' => 'subscribe', 'identifier' => { 'channel' => 'MyChannel' }, 'data' => data }.to_json
  client = WebSocket::Client::Simple.connect(url, protocol: subprotocol, header: header)

  client.on :open do
    p "opening"
    client.send message
  end

  client.on :message do |message|
    puts "Message : #{message.data}"
  end

  client.on :error do |error|
    puts "Erreur : #{error}"
  end

Thank you

unasuke commented 1 year ago

@nicohc Sorry. We couldn't help a problem or(and) question for specific product. If you have problems with this gem not working properly, please share the error and we may be able to help.

nicohc commented 1 year ago

No problem, at least, is it generally the right way to mention the protocol and the header ? I didn't see information about it in the documentation.

client = WebSocket::Client::Simple.connect(url, protocol: subprotocol, header: header)

And about the graphql query, does the gem allows it ?

unasuke commented 1 year ago

@nicohc If you pass headers ( not header ) option to connect method, it uses HTTP headers in Websocket::Handshake::Client (in websocket gem).

https://github.com/imanel/websocket-ruby/blob/v1.2.9/lib/websocket/handshake/client.rb#L53

And about the graphql query, does the gem allows it ?

This question is difficult to answer to me. Because you can do anything in a block of client.on, send http request, write logfile, and so on, of course send GraphQL request to any host too.