Last active
August 29, 2015 14:24
-
-
Save atc3/d59dfeb408dd38209a06 to your computer and use it in GitHub Desktop.
React Native - Backbone fetch patch
This file contains 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
/** | |
* patch to make backbone work on react native | |
* replaces the underlying jQuery API with the whatwg fetch API | |
* doesn't cover all use cases... but has worked fine with our project | |
*/ | |
var Backbone = require('backbone'); | |
var _ = require('underscore'); | |
Backbone.sync = function(method, model, options) { | |
var headers = { | |
'Accept': 'application/json' | |
}; | |
var body = ''; | |
var url = model.url; | |
if (!options.url) { | |
url = _.result(model, 'url'); | |
} else { | |
url = options.url; | |
} | |
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { | |
headers['Content-Type'] = 'application/json'; | |
body = JSON.stringify(options.attrs || model.toJSON(options)); | |
} | |
var methodMap = { | |
'create': 'POST', | |
'update': 'PUT', | |
'patch': 'PATCH', | |
'delete': 'DELETE', | |
'read': 'GET' | |
}; | |
method = methodMap[method]; | |
return fetch(url, { | |
method: method, | |
headers: headers, | |
body: body | |
}) | |
.then(res => { | |
var response = JSON.parse(res._bodyText); | |
options.success(response, options); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment