var request = require('./request') , _ = require('underscore') ; 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) { var options = { method: method, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json' }, body: JSON.stringify(stringifyFunctions(body || {})) }; if (opts) { if (opts.query) { options.qs = createQueryObj(opts.query); } if (opts.headers) { _.extend(options.headers, opts.headers); } } return request(url, options) .handle({ '-1': _.identity, default: function(status,result) { return JSON.parse(result); } }); } 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;