Skip to content

Instantly share code, notes, and snippets.

@roberthopman
Forked from skatkov/wip_graphql_demo.rb
Created October 25, 2018 13:36
Show Gist options
  • Save roberthopman/3af6340cee2dc2697734920aac71a385 to your computer and use it in GitHub Desktop.
Save roberthopman/3af6340cee2dc2697734920aac71a385 to your computer and use it in GitHub Desktop.
Ruby example of creating a todo and then completing it using wip.chat graphql.
# NOTE: Be sure to set the API key further down in the code!
require "net/http"
require "uri"
require "json"
class WIP
def initialize(api_key:)
@api_key = api_key
end
def create_todo(attributes = {})
query = %{
mutation createTodo {
createTodo(input: {#{serialize_attributes(attributes)}}) {
id
body
completed_at
}
}
}
json = make_request query
json["data"]["createTodo"]
end
def complete_todo(todo_id)
query = %{
mutation completeTodo {
completeTodo(id: #{todo_id}) {
id
body
completed_at
}
}
}
json = make_request query
json["data"]["completeTodo"]
end
private
def make_request(query)
uri = URI.parse("https://wip.chat/graphql")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
header = {
"Authorization": "bearer #{@api_key}",
"Content-Type": "application/json"
}
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = { query: query }.to_json
# Send the request
response = http.request(request)
json = JSON.parse(response.body)
if json.has_key? "errors"
raise json["errors"].first["message"]
end
json
end
def serialize_attributes(attributes)
attributes.collect do |k,v|
"#{k}: \"#{v}\""
end.join(", ")
end
end
# Get your API key from wip.chat/api
wip = WIP.new(api_key: "REPLACE THIS")
# Create todo
puts "Creating todo…"
todo = wip.create_todo(body:"hello test")
# The ID from the newly created todo
todo_id = todo["id"].to_i
puts "Created! ID: #{todo_id}"
puts "Todo completed_at: #{todo["completed_at"]} (empty)"
# Complete todo
puts "Completing todo with ID: #{todo_id}"
todo = wip.complete_todo(todo_id)
puts "Todo completed_at: #{todo["completed_at"]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment