var CouchDB, _ref, __hasProp = {}.hasOwnProperty; var request = require('./q-request') , _ = require('underscore') , Q = require('q'); 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); } } var req = request(url, options); var res = req.response .then(function(res) { return req.then(function(res) { return JSON.parse(res); }, function(err) { return Q.reject(JSON.parse(err)); }); }, function(err) { return Q.reject(err); }); res.response = req.response .then(function(res) { return { statusCode: res.statusCode, headers: res.headers, body: JSON.parse(res.body) }; }, function(err) { return Q.reject({error:err.message}); }); return res; } 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; } } exports.CouchDB = CouchDB;