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

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

Changes for validation

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