Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design a REST search with backbone

I'm designing an API and also consuming it with Backbone.js. Part of the API will include search operations. For example when searching for cars, I might have something like:

http://api.mysite.com/search/cars?q=volvo

With backbone, I can see two options for consuming the results.

Option 1: A search is a Collection

var CarSearch = Backbone.Collection.extend({
    model: Car,
    initialize : function(models, options){
        this.query = options.query;
    },
    url: function(){
        return "http://api.mysite.com/search/cars?q="+this.query;
    }
});

var volvos = new CarSearch([], {query:'volvo'});
volvos.fetch();

Option 2: A search is a Model, and the results are a Collection

var CarSearchResults = Backbone.Collection.extend({
    model: Car
});

var CarSearch = Backbone.Model.extend({
    defaults: {
        "query":"",
        "carSearchResults":null
    },
    url: function(){
        return "http://api.mysite.com/search/cars?q="+this.get('query');
    },
    parse: function(resp,xhr){
        resp.carSearchResults = new CarSearchResults(resp.carSearchResults);
        return resp;
    }
});

var volvoSearch = new CarSearch();
volvoSearch.set({query:'volvo'});
volvoSearch.save();

What are the advantages / disadvantages of these options? Is there a backbone-y way of designing this?

I'm leaning towards option 2 because it seems easier to add things to the response like pagination details, or a next url. But option 2 seems messier in a couple of ways. For example, would I generate an ID on the server for the search model when it is saved? Don't think I need to get that model by ID, deleting or updating it doesn't really make sense either cause I'm not persisting it.

like image 556
user1385729 Avatar asked Jun 19 '12 17:06

user1385729


1 Answers

i dont know if its a good practice, but i use for my search the "data" option in the "fetch" method.

https://stackoverflow.com/a/6659501/1067061

Maybe it helps. Good Luck!

EDIT

This is the right way to pass query parameters in your collections url, The reference to the Docs shows how to pass the data attribute in fetch options, the data attribute is actually an object with key value pairs referring to query params and their values

like image 179
Moszeed Avatar answered Sep 19 '22 13:09

Moszeed