lib/harvesting/client.rb in harvesting-0.2.0 vs lib/harvesting/client.rb in harvesting-0.3.0
- old
+ new
@@ -1,19 +1,16 @@
# frozen_string_literal: true
-
require "http"
require "json"
module Harvesting
class Client
DEFAULT_HOST = "https://api.harvestapp.com/v2"
attr_accessor :access_token, :account_id
- #
# @param opts
- #
def initialize(access_token: ENV['HARVEST_ACCESS_TOKEN'], account_id: ENV['HARVEST_ACCOUNT_ID'])
@access_token = access_token.to_s
@account_id = account_id.to_s
if @account_id.length == 0 || @access_token.length == 0
@@ -36,21 +33,32 @@
Harvesting::Models::Contact.new(result, client: self)
end
end
def time_entries(opts = {})
- Harvesting::Models::TimeEntries.new(get("time_entries", opts), client: self)
+ Harvesting::Models::TimeEntries.new(get("time_entries", opts), opts, client: self)
end
def projects(opts = {})
- Harvesting::Models::Projects.new(get("projects", opts), client: self)
+ Harvesting::Models::Projects.new(get("projects", opts), opts, client: self)
end
def tasks(opts = {})
- Harvesting::Models::Tasks.new(get("tasks", opts), client: self)
+ Harvesting::Models::Tasks.new(get("tasks", opts), opts, client: self)
end
+
+ def users(opts = {})
+ Harvesting::Models::Users.new(get("users", opts), opts, client: self)
+ end
+
+ def invoices
+ get("invoices")["invoices"].map do |result|
+ Harvesting::Models::Invoice.new(result, client: self)
+ end
+ end
+
def create(entity)
url = "#{DEFAULT_HOST}/#{entity.path}"
uri = URI(url)
response = http_response(:post, uri, body: entity.to_hash)
entity.attributes = JSON.parse(response.body)
@@ -63,23 +71,30 @@
response = http_response(:patch, uri, body: entity.to_hash)
entity.attributes = JSON.parse(response.body)
entity
end
- private
+ def delete(entity)
+ url = "#{DEFAULT_HOST}/#{entity.path}"
+ uri = URI(url)
+ response = http_response(:delete, uri)
+ raise UnprocessableRequest(response.to_s) unless response.code.to_i == 200
+ end
def get(path, opts = {})
url = "#{DEFAULT_HOST}/#{path}"
url += "?#{opts.map {|k, v| "#{k}=#{v}"}.join("&")}" if opts.any?
uri = URI(url)
response = http_response(:get, uri)
JSON.parse(response.body)
end
+ private
+
def http_response(method, uri, opts = {})
response = nil
- http = HTTP["User-Agent" => "Ruby Harvest API Sample",
+ http = HTTP["User-Agent" => "Harvesting Ruby Gem",
"Authorization" => "Bearer #{@access_token}",
"Harvest-Account-ID" => @account_id]
params = {}
if opts[:body]
params[:json] = opts[:body]