-
Notifications
You must be signed in to change notification settings - Fork 2
/
service.rb
90 lines (63 loc) · 1.67 KB
/
service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require 'net/http'
require 'uri'
require 'json'
class Service
def initialize(backend_url, repo_id, username, password)
@backend_url = backend_url
@repo_id = repo_id
@username = username
@password = password
@session = login!
end
def get_ids_for_type(record_type)
get_json("#{repo_uri}/#{plural(record_type)}", {
:all_ids => true
})
end
def get_record(uri)
get_json(uri)
end
def get_records_for_type(record_type, ids)
get_json("#{repo_uri}/#{plural(record_type)}", {
'id_set[]' => ids
})
end
def repo_uri
"/repositories/#{@repo_id}"
end
private
def get_json(path, params = {})
response = get(path, params)
JSON.parse(response.body)
end
def get(path, params = {})
url = build_url(path, params)
request = Net::HTTP::Get.new(url.request_uri)
do_http_request(url, params, request)
end
def do_http_request(url, params = {}, request)
Net::HTTP.start(url.host, url.port) {|http|
http.use_ssl = true if url.scheme == 'https'
request['X-ArchivesSpace-Session'] = @session
http.request(request)
}
end
def login!
path = "/users/#{@username}/login"
url = build_url(path)
response = Net::HTTP.post_form(url, {:password => @password, :expiring => false})
if response.code != '200'
raise LoginFailedException.new("#{response.code}: #{response.body}")
end
@session = JSON(response.body).fetch('session')
@session
end
def build_url(path, params = {})
result = URI.join(@backend_url, path.gsub(/^\//, ""))
result.query = URI.encode_www_form(params)
result
end
def plural(record_type)
"#{record_type}s"
end
end