lib/medlink/client.rb in medlink-0.1.0 vs lib/medlink/client.rb in medlink-0.2.0

- old
+ new

@@ -1,25 +1,41 @@ module Medlink class Client - def initialize(api_key) - @api_key = api_key - end + def post(url, params = {}) + response = faraday_client.post do |req| + req.url api_url(url) - attr_reader :api_key + req.headers['Authorization'] = "Token token=\"#{token}\"" + req.headers['Content-Type'] = "application/json" - def get(url, params = {}) - params[:api_key] = api_key - client.get(api_url(url), params) + 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 client - @client ||= Faraday.new(url: site) do |faraday| + 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 \ No newline at end of file