Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to handle a REST API's 'create' response in Backbone.js

I'm using backbone.js to interact with a REST API that, when posting to it to create a new resource, responds with a status of 201, a 'Location' header pointing to the resource's URI, but an empty body.

When I create a new model at the moment, its successful, but the local representation of the model only contains the properties I explicitly set, not any of the properties that would be set on the server (created_date, etc.)

From what I understand, Backbone would update its representation of the model with data in the body, if there were any. But, since there isn't, it doesn't.

So, clearly, I need to use the location in the Location header to update the model, but what's the best way to do this.

My current mindset is that I would have to parse the url from the header, split out the id, set the id for the model, then tell the model to fetch().

This seems really messy. Is there a cleaner way to do it?

I have some influence over the API. Is the best solution to try to get the API author to return the new model as the body of the response (keeping the 201 and the location header as well)?

Thanks!

like image 861
Edward M Smith Avatar asked May 21 '11 13:05

Edward M Smith


People also ask

How to integrate API in Backbone JS?

We can use the API as the link for the resource of data in our Backbone. Simply create a new collection with the URL of your resource endpoint: Syntax: var collection = Backbone.

What is backbone JS used for?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

Does backbone require jQuery?

You can use the Backbone. Model without jQuery, but Backbone. View will require either jQuery or Zepto, just like the docs state. Chances of not using view and router is low enough.

What is backbone JS model?

Model contains dynamic data and its logic. It performs various types of action on the data like validation, conversion, computed properties, access control etc. 1. It extends Backbone.


1 Answers

Sounds like you will have to do a little customization. Perhaps override the parse method and url method of your model class inherited from Backbone.Model.

The inherited functions are:

url : function() {
  var base = getUrl(this.collection);
  if (this.isNew()) return base;
  return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
},
parse : function(resp) {
  return resp;
},

and you could try something like:

parse: function(resp, xhr) {
    this._url = xhr.getResponseHeader('location')
    return resp
}
url: function() {
    return this._url
}
like image 116
34m0 Avatar answered Oct 21 '22 12:10

34m0