All files / mobile.startup/search SearchGateway.js

91.66% Statements 44/48
50% Branches 7/14
84.61% Functions 11/13
91.3% Lines 42/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198  1x 1x 1x               7x 7x 7x     1x                                     2x 2x       2x   2x 2x 2x     2x       2x                             19x 19x                             19x 19x 19x   19x                           5x             5x       5x   5x                           2x 2x   2x   2x 5x   5x     2x                         2x 2x   2x 2x     2x     2x                       2x             2x                       2x       1x  
var
	pageJSONParser = require( '../page/pageJSONParser' ),
	util = require( '../util' ),
	extendSearchParams = require( '../extendSearchParams' );
 
/**
 * @class SearchGateway
 * @uses mw.Api
 * @param {mw.Api} api
 */
function SearchGateway( api ) {
	this.api = api;
	this.searchCache = {};
	this.generator = mw.config.get( 'wgMFSearchGenerator' );
}
 
SearchGateway.prototype = {
	/**
	 * The namespace to search in.
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @type {number}
	 */
	searchNamespace: 0,
 
	/**
	 * Get the data used to do the search query api call.
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @param {string} query to search for
	 * @return {Object}
	 */
	getApiData( query ) {
		var prefix = this.generator.prefix,
			data = extendSearchParams( 'search', {
				generator: this.generator.name
			} );
 
		data.redirects = '';
 
		data['g' + prefix + 'search'] = query;
		data['g' + prefix + 'namespace'] = this.searchNamespace;
		data['g' + prefix + 'limit'] = 15;
 
		// If PageImages is being used configure further.
		Iif ( data.pilimit ) {
			data.pilimit = 15;
			data.pithumbsize = mw.config.get( 'wgMFThumbnailSizes' ).tiny;
		}
		return data;
	},
 
	/**
	 * Escapes regular expression wildcards (metacharacters) by adding a \\ prefix
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @param {string} str a string
	 * @return {Object} a regular expression that can be used to search for that str
	 * @private
	 */
	_createSearchRegEx( str ) {
		// '\[' can be unescaped, but leave it balanced with '`]'
		// eslint-disable-next-line no-useless-escape
		str = str.replace( /[-\[\]{}()*+?.,\\^$|#\s]/g, '\\$&' );
		return new RegExp( '^(' + str + ')', 'ig' );
	},
 
	/**
	 * Takes a label potentially beginning with term
	 * and highlights term if it is present with strong
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @param {string} label a piece of text
	 * @param {string} term a string to search for from the start
	 * @return {string} safe html string with matched terms encapsulated in strong tags
	 * @private
	 */
	_highlightSearchTerm( label, term ) {
		label = util.parseHTML( '<span>' ).text( label ).html();
		term = term.trim();
		term = util.parseHTML( '<span>' ).text( term ).html();
 
		return label.replace( this._createSearchRegEx( term ), '<strong>$1</strong>' );
	},
 
	/**
	 * Return data used for creating {Page} objects
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @param {string} query to search for
	 * @param {Object} pageInfo from the API
	 * @return {Object} data needed to create a {Page}
	 * @private
	 */
	_getPage( query, pageInfo ) {
		var page = pageJSONParser.parse( pageInfo );
 
		// If displaytext is set in the generator result (eg. by Wikibase),
		// use that as display title.
		// Otherwise default to the page's title.
		// FIXME: Given that displayTitle could have html in it be safe and just highlight text.
		// Note that highlightSearchTerm does full HTML escaping before highlighting.
		page.displayTitle = this._highlightSearchTerm(
			pageInfo.displaytext ? pageInfo.displaytext : page.title,
			query
		);
		page.index = pageInfo.index;
 
		return page;
	},
 
	/**
	 * Process the data returned by the api call.
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @param {string} query to search for
	 * @param {Object} data from api
	 * @return {Array}
	 * @private
	 */
	_processData( query, data ) {
		var self = this,
			results = [];
 
		Eif ( data.query ) {
 
			results = data.query.pages || {};
			results = Object.keys( results ).map( ( id ) => self._getPage( query, results[id] ) );
			// sort in order of index
			results.sort( ( a, b ) => a.index - b.index );
		}
 
		return results;
	},
 
	/**
	 * Perform a search for the given query.
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @param {string} query to search for
	 * @return {jQuery.Deferred}
	 */
	search( query ) {
		var xhr, request,
			scriptPath = mw.config.get( 'wgMFScriptPath' ),
			self = this;
 
		Eif ( !this.isCached( query ) ) {
			xhr = this.api.get( this.getApiData( query ), scriptPath ? {
				url: scriptPath
			} : undefined );
			request = xhr
				.then( ( data, jqXHR ) => {
					// resolve the Deferred object
					return {
						query,
						results: self._processData( query, data ),
						searchId: jqXHR && jqXHR.getResponseHeader( 'x-search-id' )
					};
				}, () => {
					// reset cached result, it maybe contains no value
					self.searchCache[query] = undefined;
				} );
 
			// cache the result to prevent the execution of one search query twice
			// in one session
			this.searchCache[query] = request.promise( {
				abort() {
					xhr.abort();
				}
			} );
		}
 
		return this.searchCache[query];
	},
 
	/**
	 * Check if the search has already been performed in given session.
	 *
	 * @memberof SearchGateway
	 * @instance
	 * @param {string} query
	 * @return {boolean}
	 */
	isCached( query ) {
		return Boolean( this.searchCache[query] );
	}
};
 
module.exports = SearchGateway;