request = require './q-request' _ = require 'underscore' Q = require 'q' class CouchDB constructor: (url) -> @url = normalizeURL url get: (id) -> url = "#{@url}/#{id}" couchRequest 'GET', url post: (doc) -> url = "#{@url}" couchRequest 'POST', url, doc put: (id, doc) -> url = "#{@url}/#{id}" couchRequest 'PUT', url, doc normalizeURL = (url) -> url.replace /\/$/, '' couchRequest = (method, url, data) -> options = method: method, headers: 'content-type': 'application/json; charset=utf-8' 'accept': 'application/json' body: JSON.stringify (stringifyFunctions (data || {})) request(url, options) .then (res) => JSON.parse res , (err) => Q.reject (JSON.parse err) 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