Skip to content

Commit

Permalink
Added the ability to serialize functions to JSON strings for document…
Browse files Browse the repository at this point in the history
… creation (think: views)... also made it so the default mode for saveDoc is to ignore revision conflict.
  • Loading branch information
jasonwyatt authored and sixtus committed Apr 26, 2010
1 parent 9363273 commit 2ecea22
Showing 1 changed file with 40 additions and 5 deletions.
45 changes: 40 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,15 @@ function toJSON(obj) {
// Object to convert to JSON
// returns:
// JSON string representation of obj.
return obj !== null ? JSON.stringify(obj) : null;
if(obj !== null){
return JSON.stringify(obj, function(key, val) {
if (typeof val == 'function') {
return val.toString();
}
return val;
});
}
return null;
}

var CouchDB = {
Expand Down Expand Up @@ -460,7 +468,7 @@ var CouchDB = {
this.interact("get", path, 200, options); // interact will override get to post when needed
},

saveDoc : function(doc, options) {
saveDoc : function(doc, options, enforceRevision) {
// summary:
// Creates or updates a particular document.
// description:
Expand All @@ -474,25 +482,52 @@ var CouchDB = {
// Document to save.
// options: Object
// Standard options object.
// enforceRevision: Boolean - Optional
// If true, we will enforce revision-checking when
// saving the document. Otherwise, if the document
// doesn't have a valid _rev attribute, we'll retrieve
// it and then re-try the PUT request.
options = options || {};
doc = doc || {};

var me = this;

var success = options.success;
options.success = function(result) {
if (!result.ok) {
options.error(result);
if(enforceRevision){
options.error(result);
} else {
me.openDoc(doc._id, {
success: function(existingDoc){
doc._rev = existingDoc._rev;
var opts = options;
opts.success = success;
me.saveDoc(doc,opts);
},
error: options.error
});
}
return;
} else {
doc._id = result.id;
doc._rev = result.rev;
}
if (success) { success(doc); }
if (success) {
success(doc);
}
};

options.body = doc;

if (doc._id === undefined) {
this.interact("post", "", 201, options);
} else {
this.interact("put", doc._id, 201, options);
var successCodes = [201, 409];
if(enforceRevision){
successCodes.pop();
}
this.interact("put", doc._id, successCodes, options);
}
},

Expand Down

0 comments on commit 2ecea22

Please sign in to comment.