Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use existing _id if present when creating document #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions spec/couchdb_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion src/couchdb/client.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
Expand Down