api_client.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. require 'json'
  2. require 'net/http'
  3. require 'net/http/post/multipart'
  4. require 'uri'
  5. class ApiClient
  6. def initialize(host, base_id)
  7. @host = host
  8. @current_id = Integer(base_id)
  9. end
  10. def generate_id
  11. id = @current_id
  12. @current_id += 1
  13. id
  14. end
  15. def set_auth!(username, password)
  16. @username = username
  17. @password = password
  18. end
  19. def clear_auth!
  20. @username = nil
  21. @password = nil
  22. end
  23. def request(type, path, req_body = nil)
  24. uri = URI("http://#{@host}#{path}")
  25. Net::HTTP.start(uri.host, uri.port) do |http|
  26. req_type = Net::HTTP.const_get(type)
  27. req = req_type.new(uri)
  28. if req_body
  29. req['Content-Type'] = 'application/json'
  30. req_body = req_body.to_json if !req_body.is_a?(String)
  31. req.body = req_body
  32. end
  33. if @username && @password
  34. req.basic_auth(@username, @password)
  35. end
  36. res = http.request(req)
  37. res.value
  38. body = res.body
  39. if res['content-type'].downcase == 'application/json'
  40. body = JSON.parse(body)
  41. end
  42. body
  43. end
  44. end
  45. def upload_json(path, file)
  46. `curl -s "http://#{@host}#{path}" -X POST -F 'f=@#{file}'`
  47. end
  48. def get(path)
  49. request(:Get, path)
  50. end
  51. def put(path, body)
  52. request(:Put, path, body)
  53. end
  54. def post(path, body)
  55. request(:Post, path, body)
  56. end
  57. def get_state(params = {})
  58. get("/gateways/#{params[:id]}/#{params[:type]}/#{params[:group_id]}")
  59. end
  60. def patch_state(state, params = {})
  61. put("/gateways/#{params[:id]}/#{params[:type]}/#{params[:group_id]}", state.to_json)
  62. end
  63. end