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(data = {}, params = {pgSz: 100}) ⇒ Object

add / update reports



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

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

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

get ALL records at path by paging through record set



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

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



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

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



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

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)



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

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



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

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



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

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



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

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



200
201
202
203
204
# File 'lib/collectionspace/client/helpers.rb', line 200

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, csids = []) ⇒ Object



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

def reindex_full_text(doctype, csids = [])
  if csids.any?
    run_job(
      "Reindex Full Text", :reindex_full_text, :reindex_by_csids, {doctype: doctype, csids: csids}
    )
  else
    run_job(
      "Reindex Full Text", :reindex_full_text, :reindex_by_doctype, {doctype: doctype}
    )
  end
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



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
185
186
# File 'lib/collectionspace/client/helpers.rb', line 131

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



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

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



195
196
197
198
# File 'lib/collectionspace/client/helpers.rb', line 195

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

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



206
207
208
# File 'lib/collectionspace/client/helpers.rb', line 206

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