Debian Codegraph @

dojox/data/ClientFilter.js

raw symbols SCIP
1 define(["dojo/_base/declare", "dojo/_base/lang", "dojo/_base/array", "dojo/_base/Deferred", "dojo/data/util/filter"],
2 function(declare, lang, array, Deferred, filter) {
3
4 // This is an abstract data store module for adding updatable result set functionality to an existing data store class
5
6 var addUpdate = function(store,create,remove){
7 // create a handler that adds to the list of notifications
8 return function(item){
9 store._updates.push({
10 create:create && item,
11 remove:remove && item
12 });
13 ClientFilter.onUpdate();
14 }
15 };
16 var ClientFilter = declare("dojox.data.ClientFilter", null, {
17 cacheByDefault: false,
18 constructor: function(){
19 // summary:
20 // This is an abstract class that data stores can extend to add updateable result set functionality
21 // as well as client side querying capabilities. This enables
22 // widgets to be aware of how active results change in response to the modifications/notifications.
23 // description:
24 // To a update a result set after a notification (onNew, onSet, and onDelete),
25 // widgets can call the updateResultSet method. Widgets can use the updated
26 // result sets to determine how to react to notifications, and how to update their displayed results
27 // based on changes.
28 //
29 // This module will use the best available information to update result sets, using query attribute
30 // objects to determine if items are in a result set, and using the sort arrays to maintain sort
31 // information. However, queries can be opaque strings, and this module can not update
32 // results by itself in this case. In this situations, data stores can provide a isUpdateable(request) function
33 // and matchesQuery(item,request) function. If a data store can handle a query, it can return true from
34 // isUpdateable and if an item matches a query, it can return true from matchesQuery. Here is
35 // definition of isUpdateable and matchesQuery:
36 //
37 // - isUpdateable(request) - request is the keywords arguments as is passed to the fetch function.
38 // - matchesQuery(item,request) - item is the item to test, and request is the value arguments object
39 // for the fetch function.
40 //
41 // You can define a property on this object instance "cacheByDefault" to a value of true that will
42 // cause all queries to be cached by default unless the cache queryOption is explicitly set to false.
43 // This can be defined in the constructor options for ServiceStore/JsonRestStore and subtypes.
44 //
45 // example:
46 // to make a updated-result-set data store from an existing data store:
47 // | declare("dojox.data.MyLiveDataStore",
48 // | dojox.data.MyDataStore,dojox.data.ClientFilter], // subclass LiveResultSets if available
49 // | {}
50 // | );
51 this.onSet = addUpdate(this,true,true);
52 this.onNew = addUpdate(this,true,false);
53 this.onDelete = addUpdate(this,false,true);
54 this._updates= [];
55 this._fetchCache = [];
56 },
57 clearCache: function(){
58 // summary:
59 // Clears the cache of client side queries
60 this._fetchCache = [];
61 },
62 updateResultSet: function(/*Array*/ resultSet, /*Object*/ request){
63 // summary:
64 // Attempts to update the given result set based on previous notifications
65 // resultSet:
66 // The result set array that should be updated
67 // request:
68 // This object follows the same meaning as the keywordArgs passed to a dojo/data/api/Read.fetch.
69 // description:
70 // This will attempt to update the provide result based on previous notification, adding new items
71 // from onNew calls, removing deleted items, and updating modified items, and properly removing
72 // and adding items as required by the query and sort parameters.
73 // returns:
74 // - 0: Indicates it could not successfully update the result set
75 // - 1: Indicates it could successfully handle all the notifications, but no changes were made to the result set
76 // - 2: Indicates it successfully handled all the notifications and result set has been updated.
77 if(this.isUpdateable(request)){
78 // we try to avoid rerunning notification updates more than once on the same object for performance
79 for(var i = request._version || 0; i < this._updates.length;i++){
80 // for each notification,we will update the result set
81 var create = this._updates[i].create;
82 var remove = this._updates[i].remove;
83 if(remove){
84 for(var j = 0; j < resultSet.length;j++){
85 if(this.getIdentity(resultSet[j]) == this.getIdentity(remove)){
86 resultSet.splice(j--,1);
87 var updated = true;
88 }
89 }
90 }
91 if(create && this.matchesQuery(create,request) && // if there is a new/replacement item and it matches the query
92 array.indexOf(resultSet,create) == -1){ // and it doesn't already exist in query
93 resultSet.push(create); // should this go at the beginning by default instead?
94 updated = true;
95 }
96 }
97 if(request.sort && updated){
98 // do the sort if needed
99 resultSet.sort(this.makeComparator(request.sort.concat()));
100 }
101 resultSet._fullLength = resultSet.length;
102 if(request.count && updated && request.count !== Infinity){
103 // do we really need to do this?
104 // make sure we still find within the defined paging set
105 resultSet.splice(request.count, resultSet.length);
106 }
107 request._version = this._updates.length;
108 return updated ? 2 : 1;
109 }
110 return 0;
111 },
112 querySuperSet: function(argsSuper, argsSub){
113 // summary:
114 // Determines whether the provided arguments are super/sub sets of each other
115 // argsSuper:
116 // Dojo Data Fetch arguments
117 // argsSub:
118 // Dojo Data Fetch arguments
119 if(argsSuper.query == argsSub.query){
120 return {};
121 }
122 if(!(argsSub.query instanceof Object && // sub query must be an object
123 // super query must be non-existent or an object
124 (!argsSuper.query || typeof argsSuper.query == 'object'))){
125 return false;
126 }
127 var clientQuery = lang.mixin({},argsSub.query);
128 for(var i in argsSuper.query){
129 if(clientQuery[i] == argsSuper.query[i]){
130 delete clientQuery[i];
131 }else if(!(typeof argsSuper.query[i] == 'string' &&
132 // if it is a pattern, we can test to see if it is a sub-pattern
133 // FIXME: This is not technically correct, but it will work for the majority of cases
134 filter.patternToRegExp(argsSuper.query[i]).test(clientQuery[i]))){
135 return false;
136 }
137 }
138 return clientQuery;
139 },
140 // This is the point in the version notification history at which it is known that the server is in sync, this should
141 // be updated to this._updates.length on commit operations.
142 serverVersion: 0,
143
144 cachingFetch: function(args){
145 var self = this;
146 for(var i = 0; i < this._fetchCache.length;i++){
147 var cachedArgs = this._fetchCache[i];
148 var clientQuery = this.querySuperSet(cachedArgs,args);
149 if(clientQuery !== false){
150 var defResult = cachedArgs._loading;
151 if(!defResult){
152 defResult = new Deferred();
153 defResult.callback(cachedArgs.cacheResults);
154 }
155 defResult.addCallback(function(results){
156 results = self.clientSideFetch(lang.mixin(lang.mixin({}, args),{query:clientQuery}), results);
157 defResult.fullLength = results._fullLength;
158 return results;
159 });
160 args._version = cachedArgs._version;
161 break;
162 }
163 }
164 if(!defResult){
165 var serverArgs = lang.mixin({}, args);
166 var putInCache = (args.queryOptions || 0).cache;
167 var fetchCache = this._fetchCache;
168 if(putInCache === undefined ? this.cacheByDefault : putInCache){
169 // we are caching this request, so we want to get all the data, and page on the client side
170 if(args.start || args.count){
171 delete serverArgs.start;
172 delete serverArgs.count;
173 args.clientQuery = lang.mixin(args.clientQuery || {}, {
174 start: args.start,
175 count: args.count
176 });
177 }
178 args = serverArgs;
179 fetchCache.push(args);
180 }
181 defResult= args._loading = this._doQuery(args);
182
183 defResult.addErrback(function(){
184 fetchCache.splice(array.indexOf(fetchCache, args), 1);
185 });
186 }
187 var version = this.serverVersion;
188
189 defResult.addCallback(function(results){
190 delete args._loading;
191 // update the result set in case anything changed while we were waiting for the fetch
192 if(results){
193 args._version = typeof args._version == "number" ? args._version : version;
194 self.updateResultSet(results,args);
195 args.cacheResults = results;
196 if(!args.count || results.length < args.count){
197 defResult.fullLength = ((args.start)?args.start:0) + results.length;
198 }
199 }
200 return results;
201 });
202 return defResult;
203 },
204 isUpdateable: function(/*Object*/ request){
205 // summary:
206 // Returns whether the provide fetch arguments can be used to update an existing list
207 // request:
208 // See dojo/data/api/Read.fetch request
209
210 return !request.query || typeof request.query == "object";
211 },
212 clientSideFetch: function(/*Object*/ request,/*Array*/ baseResults){
213 // summary:
214 // Performs a query on the client side and returns the results as an array
215 // request:
216 // See dojo/data/api/Read.fetch request
217 // baseResults:
218 // This provides the result set to start with for client side querying
219 if(request.queryOptions && request.queryOptions.results){
220 baseResults = request.queryOptions.results;
221 }
222 if(request.query){
223 // filter by the query
224 var results = [];
225 for(var i = 0; i < baseResults.length; i++){
226 var value = baseResults[i];
227 if(value && this.matchesQuery(value,request)){
228 results.push(baseResults[i]);
229 }
230 }
231 }else{
232 results = request.sort ? baseResults.concat() : baseResults; // we don't want to mutate the baseResults if we are doing a sort
233 }
234 if(request.sort){
235 // do the sort if needed
236 results.sort(this.makeComparator(request.sort.concat()));
237 }
238 return this.clientSidePaging(request, results);
239 },
240 clientSidePaging: function(/*Object*/ request,/*Array*/ baseResults){
241 var start = request.start || 0;
242 var finalResults = (start || request.count) ? baseResults.slice(start,start + (request.count || baseResults.length)) : baseResults;
243 finalResults._fullLength = baseResults.length;
244 return finalResults;
245 },
246 matchesQuery: function(item,request){
247 var query = request.query;
248 var ignoreCase = request.queryOptions && request.queryOptions.ignoreCase;
249 for(var i in query){
250 // if anything doesn't match, than this should be in the query
251 var match = query[i];
252 var value = this.getValue(item,i);
253 if((typeof match == 'string' && (match.match(/[\*\.]/) || ignoreCase)) ?
254 !filter.patternToRegExp(match, ignoreCase).test(value) :
255 value != match){
256 return false;
257 }
258 }
259 return true;
260 },
261 makeComparator: function(sort){
262 // summary:
263 // returns a comparator function for the given sort order array
264 // sort:
265 // See dojox.data.api.Read.fetch
266 var current = sort.shift();
267 if(!current){
268 // sort order for ties and no sort orders
269 return function(){
270 return 0;// keep the order unchanged
271 };
272 }
273 var attribute = current.attribute;
274 var descending = !!current.descending;
275 var next = this.makeComparator(sort);
276 var store = this;
277 return function(a,b){
278 var av = store.getValue(a,attribute);
279 var bv = store.getValue(b,attribute);
280 if(av != bv){
281 return av < bv == descending ? 1 : -1;
282 }
283 return next(a,b);
284 };
285 }
286 }
287 );
288 ClientFilter.onUpdate = function(){};
289
290 return ClientFilter;
291 });