request = require './q-request' _ = require 'underscore' Q = require 'q' class CouchError extends Error class CouchDB constructor: (url,db) -> @serverURL = normalizeURL url @db = db if @db @url = "#{@serverURL}/#{@db}" else @url = "#{@serverURL}" get: (id, opts) -> url = "#{@url}/#{id}" couchRequest 'GET', url, null, opts post: (doc, opts) -> url = "#{@url}/" couchRequest 'POST', url, doc, opts put: (id, doc, opts) -> url = "#{@url}/#{id}" couchRequest 'PUT', url, doc, opts delete: (id, opts) -> url = "#{@url}/#{id}" couchRequest 'DELETE', url, null, opts uuids: (opts) -> url = "#{@serverURL}/_uuids" couchRequest 'GET', url, null, opts normalizeURL = (url) -> url.replace /\/$/, '' couchRequest = (method, url, body, opts) -> options = method: method, headers: 'Content-Type': 'application/json; charset=utf-8' 'Accept': 'application/json' body: JSON.stringify (stringifyFunctions (body || {})) if opts options.qs = createQueryObj opts.query if opts.query _.extend options.headers, opts.headers if opts.headers req = request(url, options) res = req.response.then (res) => req.then (res) => JSON.parse res , (err) => Q.reject (JSON.parse err) , (err) => Q.reject err res.response = req.response.then (res) => statusCode: res.statusCode headers: res.headers body: JSON.parse res.body , (err) => Q.reject err res createQueryObj = (obj) -> newObj = {} _.each obj, (val,key) -> newObj[key] = JSON.stringify val newObj stringifyFunctions = (value) -> if value is null null else if _.isArray value value else if _.isFunction value value.toString() else if _.isObject value value = _.clone value _.each value, (propValue, propName) => value[propName] = stringifyFunctions propValue value else value exports.CouchDB = CouchDB