module Medlink class Client def post(url, params = {}) response = faraday_client.post do |req| req.url api_url(url) req.headers['Authorization'] = "Token token=\"#{token}\"" req.headers['Content-Type'] = "application/json" req.body = JSON.generate(params) end raise UnauthorizedError, "Token '#{token}' is not valid" if response.status == 401 json = JSON.parse response.body if json.is_a? Hash and json.has_key?("errors") error = json["errors"].first raise(Error, "Error #{error["code"]}: #{error["detail"]}") end json end private def faraday_client @faraday_client ||= Faraday.new(url: site) do |faraday| faraday.request :url_encoded # form-encode POST params faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end end def token Medlink.configuration.token end def site Medlink.configuration.site end def api_url(url) "/api/#{url}" end end end