Method: MarkLogic::Collection#save

Defined in:
lib/marklogic/collection.rb

#save(doc) ⇒ Object Also known as: create, insert



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/marklogic/collection.rb', line 27

def save(doc)
  if (doc.is_a?(Array))
    docs = {}
    doc.each do |d|
      docs[doc_uri(d)] = ::Oj.dump(d, mode: :compat)
    end
    body = build_multipart_body(docs)
    response = @database.connection.post_multipart("/v1/documents", body)
    raise Exception.new("Invalid response: #{response.code.to_i}, #{response.body}\n") unless response.code.to_i == 200
  else
    uri = doc_uri(doc)
    url = "/v1/documents?uri=#{uri}&format=json&collection=#{collection}"
    json = ::Oj.dump(doc, mode: :compat)
    response = @database.connection.put(url, json)
    raise Exception.new("Invalid response: #{response.code.to_i}, #{response.body}\n") unless [201, 204].include? response.code.to_i
    doc[:_id] || doc[:id] || doc['_id'] || doc['id']
  end
end