From aa48a66f14a8cfd45b95da413bbc6d001014ced0 Mon Sep 17 00:00:00 2001 From: Aaron Namba Date: Sat, 24 Nov 2018 12:37:12 +0900 Subject: [PATCH] use existing _id if present when creating document --- spec/couchdb_spec.cr | 7 +++++-- src/couchdb/client.cr | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/spec/couchdb_spec.cr b/spec/couchdb_spec.cr index 48d00f1..029034b 100644 --- a/spec/couchdb_spec.cr +++ b/spec/couchdb_spec.cr @@ -100,8 +100,11 @@ describe CouchDB do it "should get a document" do client = new_client - new_doc = client.create_document("testdb", {name: "John", age: 20}) - result = client.get_document("testdb", new_doc.id.not_nil!, Hash(String, JSON::Any)) + status = client.create_document("testdb", {_id: "john", name: "John", age: 20}) + status.ok?.should be_true + status.id.should eq "john" + + result = client.get_document("testdb", "john", Hash(String, JSON::Any)) result.should_not be_nil result.not_nil!.values_at("name", "age").should eq({"John", 20}) result.not_nil!["_id"].should_not be_nil diff --git a/src/couchdb/client.cr b/src/couchdb/client.cr index 345d64f..56874e7 100644 --- a/src/couchdb/client.cr +++ b/src/couchdb/client.cr @@ -71,7 +71,12 @@ module CouchDB end def create_document(database, object) : Response::DocumentStatus - uuid = new_uuids.first + existing_id = case object + when .responds_to?(:_id) then object._id + when .responds_to?(:[]?) then object["_id"]? || object[:_id]? + end + + uuid = existing_id || new_uuids.first Response::DocumentStatus.from_json( put(URL::DOC % {database, uuid}, body: object.to_json) )