source: Dev/trunk/src/server/util/couch.coffee @ 478

Last change on this file since 478 was 478, checked in by hendrikvanantwerpen, 12 years ago

Changes for response submission & deletion.

File size: 1.3 KB
RevLine 
[475]1request = require './q-request'
2_ = require 'underscore'
3Q = require 'q'
4
5class CouchDB
6    constructor: (url) ->
7        @url = normalizeURL url
8    get: (id) ->
9        url = "#{@url}/#{id}"
10        couchRequest 'GET', url
[477]11    post: (doc) ->
12        url = "#{@url}"
13        couchRequest 'POST', url, doc
[475]14    put: (id, doc) ->
15        url = "#{@url}/#{id}"
16        couchRequest 'PUT', url, doc
[478]17    delete: (id, rev) ->
18        url = "#{@url}/#{id}?rev=#{rev}"
19        couchRequest 'DELETE', url
[475]20
21normalizeURL = (url) ->
22    url.replace /\/$/, ''
23
24couchRequest = (method, url, data) ->
25    options =
26        method: method,
27        headers:
28            'content-type': 'application/json; charset=utf-8'
29            'accept': 'application/json'
30        body: JSON.stringify (stringifyFunctions (data || {}))
31    request(url, options)
32    .then (res) =>
33        JSON.parse res
34    , (err) =>
35        Q.reject (JSON.parse err)
36
37stringifyFunctions = (value) ->
38    if value is null
39        null
40    else if _.isArray value
41        value
42    else if _.isFunction value
43        value.toString()
44    else if _.isObject value
45        value = _.clone value
46        _.each value, (propValue, propName) =>
47            value[propName] = stringifyFunctions propValue
48        value
49    else
50        value
51
52exports.CouchDB = CouchDB
Note: See TracBrowser for help on using the repository browser.