PDA

View Full Version : Hot to change filtered query URI?



justinzane
22 May 2012, 5:17 PM
As it is, ExtJS 4.1 with a JsonRest proxy asks for a URI like this:

http://localhost:8000/api/v1/choice/?filter=[{"property":"question_id","value":2}]
my server wants filter requests to look like:

http://localhost:8000/api/v1/choice/?question_id=2
I've looked at the "filterParam" config for the proxy, but it doesn't seem relevant. Is there a practical way to achieve the request URI that the server needs?

vietits
22 May 2012, 11:21 PM
You could override <proxy>.buildUrl() to do that. Example:


Ext.onReady(function(){
var store = Ext.create('Ext.data.Store', {
fields: ['question_id'],
proxy : {
type: 'ajax',
url : 'test.cgi',
buildUrl: function(request) {
var me = this,
url = me.getUrl(request);
var params = request.params || {};
var filters = Ext.decode(params.filter);
if(filters){
delete params.filter;
Ext.Array.each(filters, function(filter){
params[filter.property] = filter.value;
})
}
if (me.noCache) {
url = Ext.urlAppend(url, Ext.String.format("{0}={1}", me.cacheString, Ext.Date.now()));
}
return url;
}
}
});


store.filter('question_id', '2');
store.load();
});

Or, you could listen for <store>.beforeload event and do handling there. Example:


Ext.onReady(function(){
var store = Ext.create('Ext.data.Store', {
fields: ['question_id'],
proxy : {
type: 'ajax',
url : 'test.cgi',
},
listeners: {
beforeload: function(store, operation){
var filters = operation.filters;
if(filters){
delete operation.filters;
operation.params = operation.params || {};
Ext.Array.each(filters, function(filter){
operation.params[filter.property] = filter.value;
});
}
}
}
});


store.filter('question_id', '2');
store.load();


});

justinzane
23 May 2012, 2:08 PM
/**
* Customized to send ../?prop=val&prop2=val2 urls.
*/
buildUrl: function(request) {
var url = this.url;
var filters = eval(request.params['filter']);
if (filters) {
delete request.params['filter'];
url += '?'
for (var i = 0; i < filters.length; i++) {
var filterString = filters[i].property + "=" + filters[i].value;
if (url.slice(url.length-1) === '?') {
url += filterString;
} else {
url += '&' + filterstring;
}
}
};
return url;
},

vietits
23 May 2012, 3:21 PM
@justinzane,

Your solution is almost the same the solution I posted. It is OK but not general. This way you will encounter problem if filter's properties and values contain special character. Also, it does not solve the problem of url caching that Ext supports. Anyway, I still recommend the solution I have posted.

justinzane
23 May 2012, 4:03 PM
You're absolutely right. I just got it to work. Now that is basically working, I'll try to learn how yours works and replace my hack with a better solution.

vietits
23 May 2012, 4:34 PM
My solution is just modifying the orginal version of buildUrl() to transform the filters to params of request and let the framework do the rest.