source: Dev/trunk/src/server/util/couch.js @ 528

Last change on this file since 528 was 528, checked in by hendrikvanantwerpen, 11 years ago

Should not need retries with new request module.

File size: 2.1 KB
Line 
1var request = require('./request')
2  , _ = require('underscore')
3  , HTTPResult = require('./http-result')
4  ;
5
6function CouchDB(url, db) {
7    this.serverURL = normalizeURL(url);
8    this.db = db;
9    if (this.db) {
10        this.url = "" + this.serverURL + "/" + this.db;
11    } else {
12        this.url = "" + this.serverURL;
13    }
14}
15
16CouchDB.prototype.get = function(id, opts) {
17    var url = "" + this.url + "/" + id;
18    return couchRequest('GET', url, null, opts);
19};
20
21CouchDB.prototype.post = function(doc, opts) {
22    var url = "" + this.url + "/";
23    return couchRequest('POST', url, doc, opts);
24};
25
26CouchDB.prototype.put = function(id, doc, opts) {
27    var url = "" + this.url + "/" + id;
28    return couchRequest('PUT', url, doc, opts);
29};
30
31CouchDB.prototype["delete"] = function(id, opts) {
32    var url = "" + this.url + "/" + id;
33    return couchRequest('DELETE', url, null, opts);
34};
35
36CouchDB.prototype.uuids = function(opts) {
37    var url = "" + this.serverURL + "/_uuids";
38    return couchRequest('GET', url, null, opts);
39};
40
41function normalizeURL(url) {
42    return url.replace(/\/$/, '');
43}
44
45function couchRequest (method, url, body, opts) {
46    body = body || {};
47    var options = {
48        method: method,
49        headers: {},
50        body: stringifyFunctions(body),
51        json: true
52    };
53    if (opts) {
54        if (opts.query) { options.qs = createQueryObj(opts.query); }
55        if (opts.headers) { _.extend(options.headers, opts.headers); }
56    }
57    return request(url, options);
58}
59
60function createQueryObj (obj) {
61    var newObj = {};
62    _.each(obj, function(val, key) {
63        newObj[key] = JSON.stringify(val);
64    });
65    return newObj;
66}
67
68function stringifyFunctions (value) {
69    if (value === null) {
70        return null;
71    } else if (_.isArray(value)) {
72        return value;
73    } else if (_.isFunction(value)) {
74        return value.toString();
75    } else if (_.isObject(value)) {
76        value = _.clone(value);
77        _.each(value, function(propValue, propName) {
78            value[propName] = stringifyFunctions(propValue);
79        });
80        return value;
81    } else {
82        return value;
83    }
84}
85
86module.exports = CouchDB;
Note: See TracBrowser for help on using the repository browser.