1 | request = require './q-request' |
---|
2 | _ = require 'underscore' |
---|
3 | Q = require 'q' |
---|
4 | |
---|
5 | class CouchError extends Error |
---|
6 | |
---|
7 | class CouchDB |
---|
8 | constructor: (url,db) -> |
---|
9 | @serverURL = normalizeURL url |
---|
10 | @db = db |
---|
11 | if @db |
---|
12 | @url = "#{@serverURL}/#{@db}" |
---|
13 | else |
---|
14 | @url = "#{@serverURL}" |
---|
15 | get: (id, opts) -> |
---|
16 | url = "#{@url}/#{id}" |
---|
17 | couchRequest 'GET', url, null, opts |
---|
18 | post: (doc, opts) -> |
---|
19 | url = "#{@url}/" |
---|
20 | couchRequest 'POST', url, doc, opts |
---|
21 | put: (id, doc, opts) -> |
---|
22 | url = "#{@url}/#{id}" |
---|
23 | couchRequest 'PUT', url, doc, opts |
---|
24 | delete: (id, opts) -> |
---|
25 | url = "#{@url}/#{id}" |
---|
26 | couchRequest 'DELETE', url, null, opts |
---|
27 | uuids: (opts) -> |
---|
28 | url = "#{@serverURL}/_uuids" |
---|
29 | couchRequest 'GET', url, null, opts |
---|
30 | |
---|
31 | normalizeURL = (url) -> |
---|
32 | url.replace /\/$/, '' |
---|
33 | |
---|
34 | couchRequest = (method, url, body, opts) -> |
---|
35 | options = |
---|
36 | method: method, |
---|
37 | headers: |
---|
38 | 'Content-Type': 'application/json; charset=utf-8' |
---|
39 | 'Accept': 'application/json' |
---|
40 | body: JSON.stringify (stringifyFunctions (body || {})) |
---|
41 | if opts |
---|
42 | options.qs = createQueryObj opts.query if opts.query |
---|
43 | _.extend options.headers, opts.headers if opts.headers |
---|
44 | req = request(url, options) |
---|
45 | res = req.response.then (res) => |
---|
46 | req.then (res) => |
---|
47 | JSON.parse res |
---|
48 | , (err) => |
---|
49 | Q.reject (JSON.parse err) |
---|
50 | , (err) => |
---|
51 | Q.reject err |
---|
52 | res.response = req.response.then (res) => |
---|
53 | statusCode: res.statusCode |
---|
54 | headers: res.headers |
---|
55 | body: JSON.parse res.body |
---|
56 | , (err) => |
---|
57 | Q.reject err |
---|
58 | res |
---|
59 | |
---|
60 | createQueryObj = (obj) -> |
---|
61 | newObj = {} |
---|
62 | _.each obj, (val,key) -> |
---|
63 | newObj[key] = JSON.stringify val |
---|
64 | newObj |
---|
65 | |
---|
66 | stringifyFunctions = (value) -> |
---|
67 | if value is null |
---|
68 | null |
---|
69 | else if _.isArray value |
---|
70 | value |
---|
71 | else if _.isFunction value |
---|
72 | value.toString() |
---|
73 | else if _.isObject value |
---|
74 | value = _.clone value |
---|
75 | _.each value, (propValue, propName) => |
---|
76 | value[propName] = stringifyFunctions propValue |
---|
77 | value |
---|
78 | else |
---|
79 | value |
---|
80 | |
---|
81 | exports.CouchDB = CouchDB |
---|