Module: CollectionSpace::Helpers

Included in:
Client
Defined in:
lib/collectionspace/client/helpers.rb

Overview

Helper methods for client requests

Instance Method Summary collapse

Instance Method Details

#add_batch(data = {}, params = {pgSz: 100}) ⇒ Object

add / update batches and data updates



14
15
16
17
18
# File 'lib/collectionspace/client/helpers.rb', line 14

def add_batch(data = {}, params = {pgSz: 100})
  payload = Template.process("batch", data)
  response = get("batch", {query: params})
  create_or_update(response, "batch", "name", data[:name], payload)
end

#add_batch_job(name, template, data = {}, params = {pgSz: 100}) ⇒ Object

add / update batch job



7
8
9
10
11
# File 'lib/collectionspace/client/helpers.rb', line 7

def add_batch_job(name, template, data = {}, params = {pgSz: 100})
  payload = Template.process(template, data)
  response = get("batch", {query: params})
  create_or_update(response, "batch", "name", name, payload)
end

#add_report(payload_path, params = {pgSz: 100}) ⇒ Object

add / update reports



21
22
23
24
25
26
# File 'lib/collectionspace/client/helpers.rb', line 21

def add_report(payload_path, params = {pgSz: 100})
  payload = File.read(File.expand_path(payload_path))
  report_name = payload.match(/<name>(.*)<\/name>/)[1]
  response = get("reports", {query: params})
  create_or_update(response, "reports", "name", report_name, payload)
end

#all(path, options = {}) ⇒ Object

get ALL records at path by paging through record set



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/collectionspace/client/helpers.rb', line 40

def all(path, options = {})
  list_type, list_item = get_list_types(path)
  iterations = (count(path).to_f / config.page_size).ceil
  return [] unless iterations.positive?

  Enumerator::Lazy.new(0...iterations) do |yielder, i|
    response = request("GET", path, options.merge(query: {pgNum: i}))
    raise CollectionSpace::RequestError, response.result.body unless response.result.success?

    items_in_page = response.parsed[list_type].fetch("itemsInPage", 0).to_i
    list_items = items_in_page.positive? ? response.parsed[list_type][list_item] : []
    list_items = [list_items] if items_in_page == 1

    yielder << list_items.shift until list_items.empty?
  end
end

#authority_doctypesObject

returns Array of authority doctypes for use in setting up batches



29
30
31
32
33
34
35
36
37
# File 'lib/collectionspace/client/helpers.rb', line 29

def authority_doctypes
  response = get("/servicegroups/authority")
  unless response.result.success?
    raise CollectionSpace::RequestError, response.result.body
  end

  result = response.result.parsed_response
  result.dig("document", "servicegroups_common", "hasDocTypes", "hasDocType")
end

#count(path) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/collectionspace/client/helpers.rb', line 57

def count(path)
  list_type, = get_list_types(path)
  response = request("GET", path, query: {pgNum: 0, pgSz: 1})
  raise CollectionSpace::RequestError, response.result.body unless response.result.success?

  response.parsed[list_type]["totalItems"].to_i
end

#domainObject

get the tenant domain from a system required top level authority (person)



66
67
68
69
70
71
72
73
# File 'lib/collectionspace/client/helpers.rb', line 66

def domain
  path = "personauthorities"
  response = request("GET", path, query: {pgNum: 0, pgSz: 1})
  raise CollectionSpace::RequestError, response.result.body unless response.result.success?

  refname = response.parsed.dig(*get_list_types(path), "refName")
  CollectionSpace::RefName.parse(refname)[:domain]
end

#find(type:, value:, subtype: nil, field: nil, schema: "common", sort: nil, operator: "=") ⇒ Object

find procedure or object by type and id find authority/vocab term by type, subtype, and refname



77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/collectionspace/client/helpers.rb', line 77

def find(type:, value:, subtype: nil, field: nil, schema: "common", sort: nil, operator: "=")
  service = CollectionSpace::Service.get(type: type, subtype: subtype)
  field ||= service[:term] # this will be set if it is an authority or vocabulary, otherwise nil
  field ||= service[:identifier]
  search_args = CollectionSpace::Search.new.from_hash(
    path: service[:path],
    namespace: "#{service[:ns_prefix]}_#{schema}",
    field: field,
    expression: "#{operator} '#{value.gsub("'", "\\\\'")}'"
  )
  search(search_args, sortBy: CollectionSpace::Search::DEFAULT_SORT)
end

#find_relation(subject_csid:, object_csid:, rel_type: nil) ⇒ Object

Parameters:

  • subject_csid (String)

    to be searched as ‘sbj` value

  • object_csid (String)

    to be searched as ‘obj` value

  • rel_type (String<'affects', 'hasBroader'>, nil) (defaults to: nil)

    to be searched as ‘prd` value



94
95
96
97
98
99
100
101
102
103
104
# File 'lib/collectionspace/client/helpers.rb', line 94

def find_relation(subject_csid:, object_csid:, rel_type: nil)
  if rel_type
    get("relations", query: {"sbj" => subject_csid, "obj" => object_csid, "prd" => rel_type})
  else
    warn(
      "No rel_type specified, so multiple types of relations between #{subject_csid} and #{object_csid} may be returned",
      uplevel: 1
    )
    get("relations", query: {"sbj" => subject_csid, "obj" => object_csid})
  end
end

#get_list_types(path) ⇒ Object



106
107
108
109
110
111
# File 'lib/collectionspace/client/helpers.rb', line 106

def get_list_types(path)
  {
    "accounts" => %w[accounts_common_list account_list_item],
    "relations" => %w[relations_common_list relation_list_item]
  }.fetch(path, %w[abstract_common_list list_item])
end

#keyword_search(type:, value:, subtype: nil, sort: nil) ⇒ Object



198
199
200
201
202
# File 'lib/collectionspace/client/helpers.rb', line 198

def keyword_search(type:, value:, subtype: nil, sort: nil)
  service = CollectionSpace::Service.get(type: type, subtype: subtype)
  options = prepare_keyword_query(value, {sortBy: CollectionSpace::Search::DEFAULT_SORT})
  request "GET", service[:path], options
end

#reindex_full_text(doctype = nil, csids = []) ⇒ Object



113
114
115
116
117
118
119
120
# File 'lib/collectionspace/client/helpers.rb', line 113

def reindex_full_text(doctype = nil, csids = [])
  run_job(
    "Reindex Full Text",
    :reindex_full_text,
    :reindex,
    {doctype: doctype, csids: csids}
  )
end

#reset_media_blob(id:, url:, verbose: false, ensure_safe_url: true, delete_existing_blob: true) ⇒ Object

Parameters:

  • id (String)

    media record’s identificationNumber value

  • url (String)

    blobUri value

  • verbose (Boolean) (defaults to: false)

    whether to put brief report of outcome to STDOUT

  • ensure_safe_url (Boolean) (defaults to: true)

    set to false if using FILE URIs or other non-HTTPS URIs

  • delete_existing_blob (Boolean) (defaults to: true)

    set to false if you have already manually deleted blobs



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/collectionspace/client/helpers.rb', line 129

def reset_media_blob(id:, url:, verbose: false,
  ensure_safe_url: true,
  delete_existing_blob: true)
  if ensure_safe_url
    unless URI.parse(url).instance_of? URI::HTTPS
      raise CollectionSpace::ArgumentError, "Not a valid url #{url}"
    end
  end

  response = find(type: "media", value: id, field: "identificationNumber")
  unless response.result.success?
    if verbose
      puts "#{id}\tfailure\tAPI request error: #{response.result.body}"
    else
      raise CollectionSpace::RequestError, response.result.body
    end
  end

  found = response.parsed
  total = found["abstract_common_list"]["totalItems"].to_i

  if total.zero?
    msg = "Media #{id} not found"
    if verbose
      puts "#{id}\tfailure\t#{msg}"
    else
      raise CollectionSpace::NotFoundError, msg
    end
  elsif total > 1
    msg = "Found multiple media records for #{id}"
    if verbose
      puts "#{id}\tfailure\t#{msg}"
    else
      raise CollectionSpace::DuplicateIdFound, msg
    end
  end

  media_uri = found["abstract_common_list"]["list_item"]["uri"]

  if delete_existing_blob
    blob_csid = found["abstract_common_list"]["list_item"]["blobCsid"]
    delete("/blobs/#{blob_csid}") if blob_csid
  end

  payload = Template.process(:reset_media_blob, {id: id})
  response = put(media_uri, payload, query: {"blobUri" => url})
  if verbose
    if response.result.success?
      puts "#{id}\tsuccess\t"
    else
      puts "#{id}\tfailure\t#{response.parsed}"
    end
  else
    response
  end
end

#run_job(name, template, invoke_template, data = {}) ⇒ Object



186
187
188
189
190
191
# File 'lib/collectionspace/client/helpers.rb', line 186

def run_job(name, template, invoke_template, data = {})
  payload = Template.process(invoke_template, data)
  job = add_batch_job(name, template)
  path = job.parsed["document"]["collectionspace_core"]["uri"]
  post(path, payload)
end

#search(query, params = {}) ⇒ Object



193
194
195
196
# File 'lib/collectionspace/client/helpers.rb', line 193

def search(query, params = {})
  options = prepare_query(query, params)
  request "GET", query.path, options
end

#service(type:, subtype: "") ⇒ Object



204
205
206
# File 'lib/collectionspace/client/helpers.rb', line 204

def service(type:, subtype: "")
  CollectionSpace::Service.get(type: type, subtype: subtype)
end