Media Types in all backbone.js REST requests
-
08-12-2019 - |
Frage
I've got an API setup which uses Media Types in the Accept header for all requests. Getting started I just simply wrapped the fetch and save functions of models, but I was curious if there was a better way rather than having to do that in every model and collection?
Update
var accountsCollection = Backbone.Collection.extend({
model: accountModel,
url: '/api/accounts',
vnd: 'application/vnd.app.AccountFeed+json',
return resp.Items;
},
search: function (q) {
this.fetch({
headers: { Accept: this.vnd },
data: {
q: q
},
success: function (data) {
//console.log(q);
}
});
}
});
As in the above example, I'm having to wrap the fetch because of the need to have a custom Accept header. In my opinion a perfect solution would be to be able to extend fetch & save to automatically pull the vnd value of the Collection or Model. I hope this better clarifies what I was asking.
Lösung
Backbone uses the notion of a sync adapter in order to customize your CRUD operation. Each collection/model can has its own sync method which could apply your custom http adapter.
Your code could look like:
var MyModel = Backbone.Model.extend({
sync: function(method, model, options) {
var options = options || {};
options.Accept = model.vnd;
return Backbone.sync(method, model, options);
}
});
Andere Tipps
Riffing off of Uzi's answer, you might also consider providing your own Backbone.sync
function. Model.fetch()
ends up delegated to the über-sync function, meaning that a patch there to include the Accept
header will ensure the header gets passed along with every request your application makes.
A good example of modifying Backbone.sync
can be found in the annotated source of the Backbone/localStorage demo.