Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require "json"
require "websocket-eventmachine-client"
require "securerandom"
require 'date'
require "base64"
API_HOST = "CHANGEME.appsync-api.ap-northeast-1.amazonaws.com"
API_KEY = "da2-CHANGEME"
REAL_TIME_HOST = API_HOST.gsub("appsync-api","appsync-realtime-api")
def authorization(options={include_user_agent: true})
#timestamp = Time.now.to_datetime.rfc3339
timestamp = `TZ=UTC date +%Y%m%dT%H%M%SZ`.chomp
hash = {
host: API_HOST,
"x-amz-date": timestamp,
"x-api-key": API_KEY
}
hash[:"x-amz-user-agent"] = "aws-amplify/2.2.2 js" if options[:include_user_agent]
hash
end
def gql_message(gql_query, gql_variables={})
uuid = SecureRandom.uuid
data = {query: gql_query, variables: gql_variables}
{
id: uuid,
payload: {
data: data.to_json,
extensions: { authorization: authorization }
},
type: "start"
}
end
def base64authorization
auth_for_connect = authorization(include_user_agent: false)
Base64.strict_encode64(auth_for_connect.to_json)
end
SERVER_URL = "wss://#{REAL_TIME_HOST}/graphql?header=#{base64authorization}&payload=e30="
HEADERS = { "Sec-WebSocket-Protocol": "graphql-ws"}
puts "Connecting to: #{SERVER_URL}"
def start_event_loop
EM.run do
trap("TERM") { stop }
trap("INT") { stop }
ws = WebSocket::EventMachine::Client.connect(uri: SERVER_URL, headers: HEADERS, debug: true, secure: true )
ws.onopen do
puts "Connected"
end
ws.onmessage do |msg, type|
puts "Received message: #{msg}"
#MESSAGES.push(msg)
end
ws.onclose do |code, reason|
puts "Disconnected with status code: #{code}"
end
EventMachine::Timer.new(5) do
ws.send gql_message("subscription { inbox(to: \"Arek\") {to, body}}").to_json
ws.send gql_message("subscription { createdEvent {id, name}}").to_json
#ws.send gql_message("{hello { greeting }}").to_json
end
def stop
puts "Terminating connection"
EventMachine.stop
end
end
end
start_event_loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.