var request = require('./request') , _ = require('underscore') , HTTPResult = require('./http-result') ; function CouchDB(url, db) { this.serverURL = normalizeURL(url); this.db = db; if (this.db) { this.url = "" + this.serverURL + "/" + this.db; } else { this.url = "" + this.serverURL; } } CouchDB.prototype.get = function(id, opts) { var url = "" + this.url + "/" + id; return couchRequest('GET', url, null, opts); }; CouchDB.prototype.post = function(doc, opts) { var url = "" + this.url + "/"; return couchRequest('POST', url, doc, opts); }; CouchDB.prototype.put = function(id, doc, opts) { var url = "" + this.url + "/" + id; return couchRequest('PUT', url, doc, opts); }; CouchDB.prototype["delete"] = function(id, opts) { var url = "" + this.url + "/" + id; return couchRequest('DELETE', url, null, opts); }; CouchDB.prototype.uuids = function(opts) { var url = "" + this.serverURL + "/_uuids"; return couchRequest('GET', url, null, opts); }; function normalizeURL(url) { return url.replace(/\/$/, ''); } function couchRequest (method, url, body, opts, retries) { body = body || {}; retries = _.isNumber(retries) ? retries : 3; var options = { method: method, headers: {}, body: stringifyFunctions(body), json: true, timeout: 5000 }; if (opts) { if (opts.query) { options.qs = createQueryObj(opts.query); } if (opts.headers) { _.extend(options.headers, opts.headers); } } return request(url, options) .handle(function(status,body){ if ( _.isUndefined(body) ) { if ( retries > 0) { return couchRequest(method,url,body,opts,retries-1); } else { return new HTTPResult(-1,new Error("No response after several retries.")); } } else { return body; } }); } function createQueryObj (obj) { var newObj = {}; _.each(obj, function(val, key) { newObj[key] = JSON.stringify(val); }); return newObj; } function stringifyFunctions (value) { if (value === null) { return null; } else if (_.isArray(value)) { return value; } else if (_.isFunction(value)) { return value.toString(); } else if (_.isObject(value)) { value = _.clone(value); _.each(value, function(propValue, propName) { value[propName] = stringifyFunctions(propValue); }); return value; } else { return value; } } module.exports = CouchDB;