api_client.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 request(type, path, req_body = nil)
  16. uri = URI("http://#{@host}#{path}")
  17. Net::HTTP.start(uri.host, uri.port) do |http|
  18. req_type = Net::HTTP.const_get(type)
  19. req = req_type.new(uri)
  20. if req_body
  21. req['Content-Type'] = 'application/json'
  22. req_body = req_body.to_json if !req_body.is_a?(String)
  23. req.body = req_body
  24. end
  25. res = http.request(req)
  26. res.value
  27. body = res.body
  28. if res['content-type'].downcase == 'application/json'
  29. body = JSON.parse(body)
  30. end
  31. body
  32. end
  33. end
  34. def upload_json(path, file)
  35. `curl -s "http://#{@host}#{path}" -X POST -F 'f=@settings.json'`
  36. end
  37. def get(path)
  38. request(:Get, path)
  39. end
  40. def put(path, body)
  41. request(:Put, path, body)
  42. end
  43. def post(path, body)
  44. request(:Post, path, body)
  45. end
  46. def get_state(params = {})
  47. get("/gateways/#{params[:id]}/#{params[:type]}/#{params[:group_id]}")
  48. end
  49. def patch_state(state, params = {})
  50. put("/gateways/#{params[:id]}/#{params[:type]}/#{params[:group_id]}", state.to_json)
  51. end
  52. end