mw.widgets.CategorySelector: Add client-side caching
authorPrateek Saxena <prtksxna@gmail.com>
Wed, 14 Sep 2016 12:15:11 +0000 (17:45 +0530)
committerPrateek Saxena <prtksxna@gmail.com>
Wed, 14 Sep 2016 12:15:32 +0000 (17:45 +0530)
The key in the cache hash is the string to be searched and
the number of the searchTypes appended as a string. This
feels a bit hacky but it'll do the job and doesn't seem
wrong.

Change-Id: Idfc931e825aaa30e00b57445d6c4afd67857609e

resources/src/mediawiki.widgets/mw.widgets.CategorySelector.js

index 7fdef25..267eebb 100644 (file)
@@ -65,6 +65,7 @@
 
                // Initialize
                this.api = config.api || new mw.Api();
+               this.searchCache = {};
        }
 
        /* Setup */
         * @return {jQuery.Promise} Resolves with an array of categories
         */
        CSP.searchCategories = function ( input, searchType ) {
-               var deferred = $.Deferred();
+               var deferred = $.Deferred(),
+                       cacheKey = input + searchType.toString();
+
+               // Check cache
+               if ( this.searchCache[ cacheKey ] !== undefined ) {
+                       return this.searchCache[ cacheKey ];
+               }
 
                switch ( searchType ) {
                        case CategorySelector.SearchType.OpenSearch:
                                        var categories = [];
 
                                        $.each( res.query.pages, function ( index, page ) {
-                                               if ( !page.missing ) {
-                                                       if ( $.isArray( page.categories ) ) {
-                                                               categories.push.apply( categories, page.categories.map( function ( category ) {
-                                                                       return category.title;
-                                                               } ) );
-                                                       }
+                                               if ( !page.missing && $.isArray( page.categories ) ) {
+                                                       categories.push.apply( categories, page.categories.map( function ( category ) {
+                                                               return category.title;
+                                                       } ) );
                                                }
                                        } );
 
                                throw new Error( 'Unknown searchType' );
                }
 
+               // Cache the result
+               this.searchCache[ cacheKey ] = deferred.promise();
+
                return deferred.promise();
        };