Created
September 23, 2015 09:40
-
-
Save iliabylich/25407f8cdab550a57b14 to your computer and use it in GitHub Desktop.
backbone_couchdb_sync
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
config.sync = | |
# ... | |
couchDB: | |
urlRoot: 'http://localhost:5984' | |
options: | |
dataType: 'json' | |
contentType: 'application/json; charset=UTF-8' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
config = require('config') | |
assert = require('utils/assert') | |
str = require('utils/string') | |
ajaxConfig = config.sync.couchDB | |
methodMap = | |
create: 'POST', | |
update: 'PUT', | |
delete: 'DELETE', | |
read: 'GET' | |
getUrl = (object, options) -> | |
parts = [ajaxConfig.urlRoot] | |
if options.url | |
parts.push options.url | |
else | |
return null unless object && object.url | |
parts.push(if assert.isFunction(object.url) then object.url() else object.url) | |
parts.join('') | |
couchDbSync = (method, model, options) -> | |
type = methodMap[method] | |
params = $.extend | |
type: type | |
beforeSend: (xhr) -> | |
model.trigger('sync:ajax:start sync:start', model) | |
, ajaxConfig.options, options | |
params.url = getUrl(model, options) | |
data = params.data | |
if method in ['create', 'update'] && !assert.isString(data) | |
if !data && model | |
if model.paramRoot | |
data = {} | |
data[model.paramRoot] = model.toJSON() | |
else | |
data = model.toJSON() | |
delete data._seq if data | |
params.data = JSON.stringify(data) if data | |
success = params.success | |
error = params.error | |
complete = params.complete | |
delete params.success | |
delete params.error | |
delete params.complete | |
$.ajax(params).done(success).fail(error).always(complete).always -> | |
model.trigger('sync:ajax:end sync:end', model) | |
module.exports = couchDbSync |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment