Best JavaScript code snippet using cypress
list.js
Source:list.js
1/*2 * ------------------------------------------3 * å表ç¼å管çå¨å®ç°æ件4 * @version 1.05 * @author genify(caijf@corp.netease.com)6 * ------------------------------------------7 */8/** @module util/cache/list */9NEJ.define([10 'base/global',11 'base/klass',12 'base/util',13 './cache.js'14],function(NEJ,_k,_u,_t,_p,_o,_f,_r){15 var _pro;16 /**17 * å表ç¼å管çå¨18 *19 * èæ¬ä¸¾ä¾20 * ```javascript21 * NEJ.define([22 * 'util/ajax/xdr',23 * 'util/cache/list'24 * ],function(_j,_t){25 * var _cache = _t._$$CacheList._$allocate({26 * id:'abc',27 * doloadlist:function(_options){28 * // ä»æå¡å¨å è½½å表29 * _j._$request(30 * '/api/list',{31 * data:_options.data,32 * onload:function(_list){33 * _options.onload(_list);34 * }35 * }36 * );37 * },38 * doloaditem:function(_options){39 * // ä»æå¡å¨å è½½æ°æ®é¡¹40 * _j._$request(41 * '/api/get',{42 * data:_options.data,43 * onload:function(_item){44 * _options.onload(_item);45 * }46 * }47 * );48 * },49 * doadditem:function(_options){50 * // å¾æå¡å¨æ·»å æ°æ®é¡¹51 * _j._$request(52 * '/api/add',{53 * data:_options.data,54 * onload:function(_item){55 * _options.onload(_item);56 * }57 * }58 * );59 * },60 * dodeleteitem:function(_options){61 * // ä»æå¡å¨å é¤æ°æ®é¡¹62 * _j._$request(63 * '/api/delete',{64 * data:_options.data,65 * onload:function(_item){66 * _options.onload(_item);67 * }68 * }69 * );70 * },71 * doupdateitem:function(_options){72 * // æ´æ°æ°æ®é¡¹è³æå¡å¨73 * _j._$request(74 * '/api/update',{75 * data:_options.data,76 * onload:function(_item){77 * _options.onload(_item);78 * }79 * }80 * );81 * },82 * dopullrefresh:function(_options){83 * // ä»æå¡å¨å è½½å表84 * _j._$request(85 * '/api/pull',{86 * data:_options.data,87 * onload:function(_list){88 * _options.onload(_list);89 * }90 * }91 * );92 * }93 * });94 *95 * // 第ä¸ä¸ªå表ç请æ±96 * _cache._$getList({key:'abc',data:{},offset:0,limit:10})97 * // ä¸ä¼å请æ±ï¼ç´æ¥èµ°ç¼å98 * _cache._$getList({key:'abc',data:{},offset:0,limit:10})99 * // 第ä¸ä¸ªé¡¹è¯·æ±100 * _cache._$getItem({id:'abc',key:'123',data:{})101 * // ä¸ä¼å请æ±ï¼ç´æ¥èµ°ç¼å102 * _cache._$getItem({id:'abc',key:'123',data:{})103 * });104 * ```105 *106 * @class module:util/cache/list._$$CacheList107 * @extends module:util/cache/cache._$$CacheAbstract108 *109 * @param {Object} config - å¯éé
ç½®åæ°110 * @property {String} id - ç¼åæ è¯ï¼é»è®¤ä½¿ç¨æé å¨ç¼å111 * @property {String} key - å表项æ è¯å段ï¼é»è®¤ä¸ºid112 * @property {Object} data - å表å
³èæ°æ®113 * @property {Boolean} autogc - æ¯å¦èªå¨æä½114 */115 /**116 * å表载å
¥å®æåè°117 * 118 * @event module:util/cache/list._$$CacheList#onlistload119 * @param {Object} event - å¯éé
ç½®åæ°120 * @property {String} key - å表æ è¯121 * @property {Variable} ext - ä¼ å
¥æ°æ®åæ ·è¿å122 */123 /**124 * ç¼å项载å
¥å®æåè°125 * 126 * @event module:util/cache/list._$$CacheList#onitemload127 * @param {Object} event - å¯éé
ç½®åæ°128 * @property {String} id - 项æ è¯129 * @property {String} key - å表æ è¯130 * @property {Variable} ext - ä¼ å
¥æ°æ®åæ ·è¿å131 */132 /**133 * ç¼å项添å å®æåè°134 * 135 * @event module:util/cache/list._$$CacheList#onitemadd136 * @param {Object} event - å¯éé
ç½®åæ°137 * @property {String} id - 项æ è¯138 * @property {String} key - å表æ è¯139 * @property {Variable} ext - ä¼ å
¥æ°æ®åæ ·è¿å140 */141 /**142 * ç¼å项å é¤å®æåè°143 * 144 * @event module:util/cache/list._$$CacheList#onitemdelete145 * @param {Object} event - å¯éé
ç½®åæ°146 * @property {String} id - 项æ è¯147 * @property {String} key - å表æ è¯148 * @property {Variable} ext - ä¼ å
¥æ°æ®åæ ·è¿å149 */150 /**151 * ç¼å项æ´æ°å®æåè°152 * 153 * @event module:util/cache/list._$$CacheList#onitemupdate154 * @param {Object} event - å¯éé
ç½®åæ°155 * @property {String} id - 项æ è¯156 * @property {String} key - å表æ è¯157 * @property {Variable} ext - ä¼ å
¥æ°æ®åæ ·è¿å158 */159 /**160 * æå¡å¨ææ°å表æåå®æåè°161 * 162 * @event module:util/cache/list._$$CacheList#onpullrefresh163 * @param {Object} event - å¯éé
ç½®åæ°164 * @property {String} key - å表æ è¯165 * @property {Variable} ext - ä¼ å
¥æ°æ®åæ ·è¿å166 */167 /**168 * ä»æå¡å¨è½½å
¥å表169 * 170 * @event module:util/cache/list._$$CacheList#doloadlist171 * @param {Object} event - å¯éé
ç½®åæ°172 * @property {String} key - å表æ è¯173 * @property {Variable} ext - åè°åä¼ æ°æ®174 * @property {Number} data - éè¦æ交å°æå¡å¨çå
¶ä»ä¿¡æ¯175 * @property {Number} offset - å移é176 * @property {Number} limit - æ°é177 * @property {Function} onload - 请æ±åè°178 */179 /**180 * ä»æå¡å¨è½½å
¥æ°æ®é¡¹181 * 182 * @event module:util/cache/list._$$CacheList#doloaditem183 * @param {Object} event - å¯éé
ç½®åæ°184 * @property {String} id - 项æ è¯185 * @property {String} key - å表æ è¯186 * @property {Variable} ext - åè°åä¼ æ°æ®187 * @property {Number} data - éè¦æ交å°æå¡å¨çå
¶ä»ä¿¡æ¯188 * @property {Function} onload - 请æ±åè°189 */190 /**191 * å¾æå¡å¨æ·»å æ°æ®é¡¹192 * 193 * @event module:util/cache/list._$$CacheList#doadditem194 * @param {Object} event - å¯éé
ç½®åæ°195 * @property {String} key - å表æ è¯196 * @property {Variable} ext - åè°åä¼ æ°æ®197 * @property {String} data - æ°æ®é¡¹å¯¹è±¡198 * @property {Function} onload - 请æ±åè°199 */200 /**201 * ä»æå¡å¨å é¤æ°æ®é¡¹202 * 203 * @event module:util/cache/list._$$CacheList#dodeleteitem204 * @param {Object} event - å¯éé
ç½®åæ°205 * @property {String} key - å表æ è¯206 * @property {Variable} ext - åè°åä¼ æ°æ®207 * @property {String} data - æ°æ®é¡¹å¯¹è±¡208 * @property {Function} onload - 请æ±åè°209 */210 /**211 * æ´æ°æå¡å¨æ°æ®é¡¹212 * 213 * @event module:util/cache/list._$$CacheList#doupdateitem214 * @param {Object} event - å¯éé
ç½®åæ°215 * @property {String} key - å表æ è¯216 * @property {Variable} ext - åè°åä¼ æ°æ®217 * @property {String} data - æ°æ®é¡¹å¯¹è±¡218 * @property {Function} onload - 请æ±åè°219 */220 /**221 * ä»æå¡å¨æåææ°å表222 * 223 * @event module:util/cache/list._$$CacheList#dopullrefresh224 * @param {Object} event - å¯éé
ç½®åæ°225 * @property {String} key - å表æ è¯226 * @property {Variable} ext - åè°åä¼ æ°æ®227 * @property {Function} onload - 请æ±åè°228 */229 _p._$$CacheList = _k._$klass();230 _pro = _p._$$CacheList._$extend(_t._$$CacheAbstract);231 /**232 * æ§ä»¶éç½®233 * 234 * @protected235 * @method module:util/cache/list._$$CacheList#__reset236 * @param {Object} arg0 - å¯éé
ç½®åæ°237 * @return {Void}238 */239 _pro.__reset = function(_options){240 this.__super(_options);241 this.__key = _options.key||'id';242 this.__data = _options.data||_o;243 this.__auto = !!_options.autogc;244 this.__doSwapCache(_options.id);245 };246 /**247 * æ§ä»¶éæ¯248 * 249 * @protected250 * @method module:util/cache/list._$$CacheList#__destroy251 * @param {Object} arg0 - å¯éé
ç½®åæ°252 * @return {Void}253 */254 _pro.__destroy = function(){255 this.__super();256 // check gc schedule257 if (!!this.__timer){258 this.__doGCAction();259 }260 };261 /**262 * åæ¢ç¼å263 * 264 * @protected265 * @method module:util/cache/list._$$CacheList#__doSwapCache266 * @param {String} arg0 - ç¼åæ è¯267 * @return {Void}268 */269 _pro.__doSwapCache = function(_id){270 var _cache;271 if (!!_id){272 _cache = this.__cache[_id];273 if (!_cache){274 _cache = {};275 this.__cache[_id] = _cache;276 }277 }278 _cache = _cache||this.__cache;279 _cache.hash = _cache.hash||{};280 // hash [Object] - item map by id281 // list [Array] - default list282 // x-list [Array] - list with key 'x'283 this.__lspl = _cache;284 };285 /**286 * æ§è¡GCè¡ä¸º287 * 288 * @protected289 * @method module:util/cache/list._$$CacheList#__doGCAction290 * @return {Void}291 */292 _pro.__doGCAction = function(){293 this.__timer = window.clearTimeout(this.__timer);294 // dump id map for used items295 var _map = {};296 _u._$loop(297 this.__lspl,function(_list,_key){298 if (_key=='hash') return;299 if (!_u._$isArray(_list)) return;300 _u._$forEach(_list,function(_item){301 if (!_item) return;302 _map[_item[this.__key]] = !0;303 },this);304 },this305 );306 // check used in hash307 _u._$loop(308 this.__getHash(),309 function(_item,_id,_hash){310 if (!_map[_id]){311 delete _hash[_id];312 }313 }314 );315 };316 /**317 * è°åº¦æ§è¡GCæä½ï¼å é¤ä¸ç¨çæ°æ®å¯¹è±¡318 * 319 * @protected320 * @method module:util/cache/list._$$CacheList#__doGCSchedule321 * @return {Void}322 */323 _pro.__doGCSchedule = function(){324 if (!!this.__timer){325 this.__timer = window.clearTimeout(this.__timer);326 }327 this.__timer = window.setTimeout(328 this.__doGCAction._$bind(this),150329 );330 };331 /**332 * ç¼åå表项333 * 334 * @protected335 * @method module:util/cache/list._$$CacheList#__doSaveItemToCache336 * @param {Object|Array} arg0 - å表项æå表337 * @param {String} arg1 - å表æ è¯338 * @return {Object|Array} ç¼åä¸å表项æå表339 */340 _pro.__doSaveItemToCache = function(_item,_lkey){341 // save item to cache342 if (!_u._$isArray(_item)){343 _item = this.__doFormatItem(_item,_lkey)||_item;344 if (!_item) return null;345 var _key = _item[this.__key];346 if (_key!=null){347 var _itm = this.__getHash()[_key];348 if (!!_itm){349 _item = _u._$merge(_itm,_item);350 }351 this.__getHash()[_key] = _item;352 }353 delete _item.__dirty__;354 return _item;355 }356 // batch save to cache357 var _result = [];358 _u._$forEach(359 _item,function(_it){360 _result.push(361 this.__doSaveItemToCache(_it,_lkey)362 );363 },this364 );365 return _result;366 };367 /**368 * ä»ç¼åå表å é¤é¡¹369 * 370 * @protected371 * @method module:util/cache/list._$$CacheList#__doRemoveItemFromList372 * @param {String} arg0 - å表æ è¯373 * @param {String|Array} arg1 - 项æ è¯,['111',{id:'222',...},...]374 * @return {Object|Array} å é¤é¡¹375 */376 _pro.__doRemoveItemFromList = function(_lkey,_id){377 var _result = null,378 _pkey = this.__key;379 // remove one item380 if (!_u._$isArray(_id)){381 var _result = null,382 _pkey = this.__key;383 _id = _id[_pkey]||_id;384 var _list = this._$getListInCache(_lkey),385 _index = _u._$indexOf(_list,function(_itm){386 return !!_itm&&_itm[_pkey]==_id;387 });388 if (_index>=0){389 _result = _list[_index];390 _list.splice(_index,1);391 }392 return _result;393 }394 // batch remove items395 var _result = [];396 _u._$reverseEach(397 _id,function(_item){398 _result.unshift(399 this.__doRemoveItemFromList(_lkey,_item)400 );401 },this402 );403 return _result;404 };405 /**406 * æ ¼å¼åæ°æ®é¡¹ï¼åç±»å®ç°å
·ä½ä¸å¡é»è¾407 * 408 * @protected409 * @method module:util/cache/list._$$CacheList#__doFormatItem410 * @param {Object} arg0 - å表项411 * @param {String} arg1 - å表æ è¯412 * @return {Object} æ ¼å¼ååçå表项413 */414 _pro.__doFormatItem = _f;415 /**416 * åå追å å表项è³å表417 * 418 * @protected419 * @method module:util/cache/list._$$CacheList#__doUnshiftToList420 * @param {String} arg0 - å表æ è¯421 * @param {Object|Array} arg1 - å表项æè
å表422 * @return {Void}423 */424 _pro.__doUnshiftToList = function(_key,_item){425 if (!_item) return;426 // item unshift427 if (!_u._$isArray(_item)){428 var _list = this._$getListInCache(_key),429 _item = this.__doSaveItemToCache(_item,_key);430 if (!!_item) _list.unshift(_item);431 return;432 }433 // batch unshift434 _u._$reverseEach(435 _item,function(_it){436 this.__doUnshiftToList(_key,_it);437 }438 );439 };440 /**441 * 设置å表æ»æ°442 *443 * èæ¬ä¸¾ä¾444 * ```javascript445 * // å表æ»æ°å·²ç¥çæ
åµï¼è¿æ¶åçtotalæ¯100446 * // å 为è¿ä¸ª100æ¯ç¬¬ä¸æ¬¡è¯·æ±ï¼ä»æå¡å¨å¸¦è¿æ¥çç¼åçï¼åç»å¯è½ä¼åå447 * // ä½æ¯å½å页é¢çæ»é¡µé¢æ æ³ååºè¿ç§éåºï¼æ以ä¸ç¨æç¸åºçåå448 * // 注æï¼cacheæ¯æ æ³ä¿è¯æ°æ®çåæ¥çãå¦æå¨å«çå°æ¹ææ°æ®å é¤ï¼cacheæ æ³è·ç¥ï¼éè¦å·æ°é¡µé¢449 * _cc._$setTotal('abc',100);450 *451 * // å表æ»æ°æªç¥çæ
åµï¼è¿æ¶åçtotalæ¯listçé¿åº¦452 * // æªç¥æ»é¿åº¦ä¼ææ´å¤é项åºç°453 * var _total = _cc._$getTotal('abc');454 * // å¦æoffset+limit>_total说æå·²ç»æ²¡ææ°æ®äºï¼ææ´å¤éèæ455 * // å¦åä¼ç»§ç»æä¸ä¸ªæ´å¤é项å¨æ«å°¾456 * ```457 *458 * @method module:util/cache/list._$$CacheList#_$setTotal459 * @see module:util/cache/list._$$CacheList#_$getTotal460 * @param {String} arg0 - å表ç¼åé®å¼461 * @param {Number} arg1 - å表æ»æ°462 * @return {Void}463 */464 _pro._$setTotal = function(_key,_total){465 var _list = this._$getListInCache(_key);466 _list.length = Math.max(_list.length,_total);467 this._$setLoaded(_key);468 };469 /**470 * åå表æ»é¿åº¦471 *472 * èæ¬ä¸¾ä¾473 * ```javascript474 * // è·åå表æ»é¿åº¦ï¼æªç¥é¡µç çæ
åµæ¯totalålist.lengthè¾é¿çä¸ä¸ª475 * // 页é¢å·²ç¥çæ
åµï¼åtotalçå¼476 * // 以ä¸å¼è¢«è®¾ç½®å°listçlengthå±æ§ä¸477 * _cc._$getTotal('abc');478 * ```479 *480 * @method module:util/cache/list._$$CacheList#_$getTotal481 * @see module:util/cache/list._$$CacheList#_$setTotal482 * @param {String} arg0 - å表æ è¯483 * @return {Number} å表æ»é¿åº¦484 */485 _pro._$getTotal = function(_key){486 return this._$getListInCache(_key).length;487 };488 /**489 * 设置æªç¥é¿åº¦å表çè½½å
¥å®ææ å¿490 *491 * èæ¬ä¸¾ä¾492 * ```javascript493 * // 设置key为abcçå®æ´æ°æ®å·²ç»è½½å
¥å®æ494 * _cc._$setLoaded('abc');495 * ```496 *497 * @method module:util/cache/list._$$CacheList#_$setLoaded498 * @param {String} arg0 - å表æ è¯499 * @return {Void}500 */501 _pro._$setLoaded = function(_key,_loaded){502 this._$getListInCache(_key).loaded = _loaded!==!1;503 };504 /**505 * å¤æå表æ¯å¦è½½å
¥å®æ506 *507 * @method module:util/cache/list._$$CacheList#_$isLoaded508 * @param {String} arg0 - å表æ è¯509 * @return {Boolean} æ¯å¦è½½å
¥å®æ510 */511 _pro._$isLoaded = function(_key){512 return !!this._$getListInCache(_key).loaded;513 };514 /**515 * 设置å表ï¼æ¸
é¤åæå表516 *517 * èæ¬ä¸¾ä¾518 * ```javascript519 * // 设置å表520 * _cc._$setListInCache('abc',[]);521 * ```522 *523 * @method module:util/cache/list._$$CacheList#_$setListInCache524 * @param {String} arg0 - å表æ è¯525 * @return {Array} å表526 */527 _pro._$setListInCache = function(_key,_list){528 this._$clearListInCache(_key);529 this.__getList({530 key:_key,531 offset:0,532 limit:_list.length+1533 },{534 list:_list,535 total:_list.length536 });537 };538 /**539 * ç´æ¥ä»ç¼åä¸åå表540 *541 * èæ¬ä¸¾ä¾542 * ```javascript543 * // ä»cacheéåå表æ°æ®544 * _cc._$getListInCache('abc');545 * ```546 *547 * @method module:util/cache/list._$$CacheList#_$getListInCache548 * @param {String} arg0 - å表æ è¯549 * @return {Array} å表550 */551 _pro._$getListInCache = (function(){552 var _doFormatKey = function(_key){553 return (_key||'')+(!_key?'':'-')+'list';554 };555 return function(_key){556 var _key = _doFormatKey(_key),557 _list = this.__lspl[_key];558 if (!_list){559 _list = [];560 this.__lspl[_key] = _list;561 }562 return _list;563 };564 })();565 /**566 * åHashæ å°è¡¨567 * 568 * @protected569 * @method module:util/cache/list._$$CacheList#__getHash570 * @return {Object} æ å°è¡¨571 */572 _pro.__getHash = function(){573 var _hash = this.__lspl.hash;574 if (!_hash){575 _hash = {};576 this.__lspl.hash = _hash;577 }578 return _hash;579 };580 /**581 * ååå·æ°å表582 * 583 * @method module:util/cache/list._$$CacheList#_$pullRefresh584 * @param {Object} arg0 - å¯éé
ç½®åæ°585 * @property {String} key - å表æ è¯586 * @property {Number} data - åéå°æå¡å¨æ°æ®ä¿¡æ¯587 * @return {Void}588 */589 _pro._$pullRefresh = (function(){590 var _doFormatKey = function(_options){591 return 'r-'+_options.key;592 };593 return function(_options){594 var _ropt = _u._$merge({},_options),595 _rkey = _doFormatKey(_ropt),596 _callback = this._$dispatchEvent._$bind(this);597 if (!this.__doQueueRequest(_rkey,_callback)){598 _ropt.rkey = _rkey;599 _ropt.onload = this.__pullRefresh._$bind(this,_ropt);600 this._$dispatchEvent('dopullrefresh',_ropt);601 }602 };603 })();604 /**605 * åååå表åè°606 * 607 * @protected608 * @method module:util/cache/list._$$CacheList#__pullRefresh609 * @param {Object} arg0 - 请æ±ä¿¡æ¯610 * @param {Array} arg1 - æ°æ®å表611 * @return {Void}612 */613 _pro.__pullRefresh = function(_options,_result){614 // list with total615 // {total:12,result:[]} æè
{total:13,list:[]}616 var _key = _options.key,617 _total = parseInt(_result.total),618 _list = _result.list||_result.result;619 this.__doUnshiftToList(_key,_list||_result);620 if (!isNaN(_total)&&!!_list){621 this._$getListInCache(_key).length = _total;622 this._$setLoaded(_key);623 }624 this.__doCallbackRequest(625 _options.rkey,'onpullrefresh',_options626 );627 };628 /**629 * åå表630 *631 * èæ¬ä¸¾ä¾632 * ```javascript633 * _cc._$getList({key:'abc',data:{},offset:0,limit:10});634 * ```635 *636 * @method module:util/cache/list._$$CacheList#_$getList637 * @param {Object} arg0 - å¯éé
ç½®åæ°638 * @property {String} key - å表æ è¯639 * @property {Number} data - å
¶ä»æ°æ®ä¿¡æ¯640 * @property {Number} offset - å移é641 * @property {Number} limit - æ°é642 * @property {Object} ext - åä¼ æ°æ®643 * @return {Void}644 */645 _pro._$getList = (function(){646 var _doFormatKey = function(_options){647 return 'r-'+648 _options.key+'-'+649 _options.offset+'-'+650 _options.limit;651 };652 return function(_options){653 _options = _options||_o;654 var _ropt = {655 key:(''+_options.key)||'',656 ext:_options.ext||null,657 data:_options.data||null,658 offset:parseInt(_options.offset)||0,659 limit:parseInt(_options.limit)||0660 },661 _list = this._$getListInCache(_ropt.key),662 _has = this.__hasFragment(663 _list,_ropt.offset,_ropt.limit664 );665 // hit in memory666 if (_has){667 this._$dispatchEvent('onlistload',_ropt);668 return;669 }670 // load from server671 var _rkey = _doFormatKey(_ropt),672 _callback = this._$dispatchEvent._$bind(this);673 if (!this.__doQueueRequest(_rkey,_callback)){674 _ropt.rkey = _rkey;675 _ropt.onload = this.__getList._$bind(this,_ropt);676 this._$dispatchEvent('doloadlist',_ropt);677 }678 };679 })();680 /**681 * åå表åè°682 * 683 * @protected684 * @method module:util/cache/list._$$CacheList#__getList685 * @param {Object} arg0 - 请æ±ä¿¡æ¯686 * @param {Array|Object} arg1 - æ°æ®å表ï¼æè
带æ»æ°ä¿¡æ¯å表687 * @return {Void}688 */689 _pro.__getList = (function(){690 var _doClear = function(_item,_index,_list){691 if (!!_item){692 return !0;693 }694 _list.splice(_index,1);695 };696 return function(_options,_result){697 _options = _options||_o;698 // clear lock if no result699 if (!_result){700 // do callback701 this.__doCallbackRequest(702 _options.rkey,'onlistload',_options703 );704 return;705 }706 // save list to cache707 var _key = _options.key,708 _offset = _options.offset,709 _chlist = this._$getListInCache(_key);710 // list with total711 // {total:12,result:[]} æè
{total:13,list:[]}712 var _list = _result||[];713 if (!_u._$isArray(_list)){714 _list = _result.result||_result.list||[];715 var _total = parseInt(_result.total);716 if (!isNaN(_total)||_total>_list.length){717 this._$setTotal(_key,_total);718 }719 }720 // merge list721 _u._$forEach(722 _list,function(_item,_index){723 _chlist[_offset+_index] = this.724 __doSaveItemToCache(_item,_key);725 },this726 );727 // check list all loaded728 if (_list.length<_options.limit){729 this._$setLoaded(_key);730 _u._$reverseEach(_chlist,_doClear);731 }732 // do callback733 this.__doCallbackRequest(734 _options.rkey,'onlistload',_options735 );736 };737 })();738 /**739 * æ¸
é¤ç¼åå表740 *741 * èæ¬ä¸¾ä¾742 * ```javascript743 * // åå表æ°æ®744 * _cc._$clearListInCache('abc');745 * ```746 *747 * @method module:util/cache/list._$$CacheList#_$clearListInCache748 * @param {String} arg0 - å表æ è¯749 * @return {Void}750 */751 _pro._$clearListInCache = (function(){752 var _doClear = function(_item,_index,_list){753 _list.splice(_index,1);754 };755 return function(_key){756 if (!!_key){757 // clear one list758 var _list = this._$getListInCache(_key);759 _u._$reverseEach(_list,_doClear);760 this._$setLoaded(_key,!1);761 if (this.__auto){762 this.__doGCSchedule();763 }764 }else{765 // clear all list766 _u._$loop(767 this.__lspl,function(_list,_key){768 if (_key=='hash'||769 !_u._$isArray(_list)) return;770 _key = _key.substr(0,_key.length-5);771 this._$clearListInCache(_key);772 },this773 );774 }775 };776 })();777 /**778 * éªè¯é¡¹ç¼åä¸ç项æ¯å¦ææï¼åç±»å¯éå779 * 780 * @protected781 * @method module:util/cache/list._$$CacheList#__doCheckItemValidity782 * @param {Object} arg0 - æ°æ®é¡¹783 * @param {String} arg0 - å表æ è¯784 * @return {Boolean} æ¯å¦ææ785 */786 _pro.__doCheckItemValidity = function(_item,_lkey){787 return !_item.__dirty__;788 };789 /**790 * ä»ç¼åä¸åå表项791 *792 * èæ¬ä¸¾ä¾793 * ```javascript794 * // ä»cacheä¸åæä¸é¡¹æ°æ®795 * _cc._$getItemInCache('abc');796 * ```797 *798 * @method module:util/cache/list._$$CacheList#_$getItemInCache799 * @param {String} arg0 - 项æ è¯800 * @return {Variable} å表项801 */802 _pro._$getItemInCache = function(_id){803 return this.__getHash()[_id];804 };805 /**806 * æ¸
é¤ç¼å项807 * 808 * @method module:util/cache/list._$$CacheList#_$clearItemInCache809 * @param {String} arg0 - 项æ è¯810 * @return {Void}811 */812 _pro._$clearItemInCache = function(_id){813 var _item = this._$getItemInCache(_id);814 if (!!_item) _item.__dirty__ = !0;815 };816 /**817 * åå表项项818 *819 * èæ¬ä¸¾ä¾820 * ```javascript821 * // åæä¸é¡¹æ°æ®822 * _cc._$getItem({823 * id:'aaaa',824 * key:'xxxxxx'825 * });826 * ```827 *828 * @method module:util/cache/list._$$CacheList#_$getItem829 * @param {Object} event - 请æ±ä¿¡æ¯830 * @property {String} id - 项æ è¯ï¼è¯¥å称ä¸é
ç½®ç项æ è¯é®ä¸è´831 * @property {String} key - å表æ è¯832 * @property {Object} data - åéå°æå¡å¨çæ°æ®833 * @property {Object} ext - éè¦åä¼ çæ°æ®ä¿¡æ¯834 * @return {Void}835 */836 _pro._$getItem = (function(){837 var _doFormatKey = function(_options){838 return 'r-'+_options.key+'-'+_options.id;839 };840 return function(_options){841 _options = _options||_o;842 var _id = _options[this.__key],843 _ropt = {844 id:_id,845 ext:_options.ext,846 data:_options.data||{},847 key:(''+_options.key)||''848 };849 _item = this._$getItemInCache(_id);850 _ropt.data[this.__key] = _id;851 // hit in memory852 if (!!_item&&853 this.__doCheckItemValidity(_item,_ropt.key)){854 this._$dispatchEvent('onitemload',_ropt);855 return;856 }857 // load from server858 var _rkey = _doFormatKey(_ropt),859 _callback = this._$dispatchEvent._$bind(this);860 if (!this.__doQueueRequest(_rkey,_callback)){861 _ropt.rkey = _rkey;862 _ropt.onload = this.__getItem._$bind(this,_ropt);863 this._$dispatchEvent('doloaditem',_ropt);864 }865 };866 })();867 /**868 * åå表项åè°869 * 870 * @protected871 * @method module:util/cache/list._$$CacheList#__getItem872 * @param {Object} arg0 - 请æ±ä¿¡æ¯873 * @param {Object} arg1 - å表项对象874 * @return {Void}875 */876 _pro.__getItem = function(_options,_item){877 _options = _options||_o;878 this.__doSaveItemToCache(_item,_options.key);879 this.__doCallbackRequest(880 _options.rkey,'onitemload',_options881 );882 };883 /**884 * æ·»å å表项885 *886 * èæ¬ä¸¾ä¾887 * ```javascript888 * _cc._$addItem({889 * key: '123',890 * item: {},891 * push: false,892 * offset:0893 * });894 * ```895 *896 * @method module:util/cache/list._$$CacheList#_$addItem897 * @param {Object} arg0 - é
置信æ¯898 * @property {String} key - å表æ è¯899 * @property {Object} data - å表项æ°æ®900 * @property {Boolean} push - æ¯å¦è¿½å å°å表尾é¨901 * @property {Number} offset - 对äºéå°¾é¨è¿½å ç项å¯éè¿æ¤åæ°æå®è¿½å ä½ç½®902 * @return {Void}903 */904 _pro._$addItem = function(_options){905 _options = _u._$merge({},_options);906 _options.onload = this.__addItem._$bind(this,_options);907 this._$dispatchEvent('doadditem',_options);908 };909 /**910 * æ·»å å表项åè°911 * 912 * @protected913 * @method module:util/cache/list._$$CacheList#__addItem}914 * @param {Object} arg0 - 请æ±ä¿¡æ¯915 * @param {Object} arg1 - å表项对象916 * @return {Void}917 */918 _pro.__addItem = function(_options,_item){919 var _key = _options.key;920 _item = this.__doSaveItemToCache(_item,_key);921 // add to list922 if (!!_item){923 var _flag = 0,924 _list = this._$getListInCache(_key);925 if (!_options.push){926 _flag = -1;927 var _offset = _options.offset||0;928 _list.splice(_offset,0,_item);929 }else if(_list.loaded){930 _flag = 1;931 _list.push(_item);932 }else{933 // add total934 _list.length++;935 }936 }937 // callback938 var _event = {939 key:_key,940 flag:_flag,941 data:_item,942 action:'add',943 ext:_options.ext944 };945 this._$dispatchEvent('onitemadd',_event);946 return _event;947 };948 /**949 * å é¤å表项950 *951 * èæ¬ä¸¾ä¾952 * ```javascript953 * _cc._$deleteItem({954 * key: '123'955 * });956 * ```957 *958 * @method module:util/cache/list._$$CacheList#_$deleteItem959 * @param {Object} arg0 - é
置信æ¯960 * @property {String} key - å表æ è¯961 * @property {String} id - å表项æ è¯962 * @property {Object} data - å表项æ°æ®ä¿¡æ¯963 * @property {Object} ext - éè¦åä¼ çæ°æ®ä¿¡æ¯964 * @return {Void}965 */966 _pro._$deleteItem = function(_options){967 _options = _u._$merge({},_options);968 _options.onload = this.__deleteItem._$bind(this,_options);969 this._$dispatchEvent('dodeleteitem',_options);970 };971 /**972 * å é¤å表项åè°973 * 974 * @protected975 * @method module:util/cache/list._$$CacheList#__deleteItem976 * @param {Object} arg0 - 请æ±ä¿¡æ¯977 * @param {Boolean} arg1 - æ¯å¦å é¤æå978 * @return {Void}979 */980 _pro.__deleteItem = function(_options,_isok){981 var _item,982 _key = _options.key;983 // sync memory984 if (!!_isok){985 var _id = _options.id;986 _item = this._$getItemInCache(_id)||null;987 this.__doRemoveItemFromList(_key,_id);988 }989 // callback990 var _event = {991 key:_key,992 data:_item,993 action:'delete',994 ext:_options.ext995 };996 this._$dispatchEvent('onitemdelete',_event);997 return _event;998 };999 /**1000 * æ´æ°å表项1001 *1002 * èæ¬ä¸¾ä¾1003 * ```javascript1004 * _cc._$updateItem({1005 * key:'123',1006 * item:{}1007 * });1008 * ```1009 *1010 * @method module:util/cache/list._$$CacheList#_$updateItem1011 * @param {Object} arg0 - é
置信æ¯1012 * @property {String} key - å表æ è¯1013 * @property {Object} data - å表项æ°æ®1014 * @property {Object} ext - éè¦åä¼ çæ°æ®ä¿¡æ¯1015 * @return {Void}1016 */1017 _pro._$updateItem = function(_options){1018 _options = _u._$merge({},_options);1019 _options.onload = this.__updateItem._$bind(this,_options);1020 this._$dispatchEvent('doupdateitem',_options);1021 };1022 /**1023 * æ´æ°å表项åè°1024 * 1025 * @protected1026 * @method module:util/cache/list._$$CacheList#__updateItem1027 * @param {Object} arg0 - 请æ±ä¿¡æ¯1028 * @param {Object} arg1 - å表项对象1029 * @return {Void}1030 */1031 _pro.__updateItem = function(_options,_item){1032 var _key = _options.key;1033 // update memory1034 if (!!_item){1035 _item = this.__doSaveItemToCache(_item,_key);1036 }1037 // callback1038 var _event = {1039 key:_key,1040 data:_item,1041 action:'update',1042 ext:_options.ext1043 };1044 this._$dispatchEvent('onitemupdate',_event);1045 return _event;1046 };1047 if (CMPT){1048 NEJ.P('nej.ut')._$$ListCache = _p._$$CacheList;1049 }1050 return _p;...
plan_cache_list_plans.js
Source:plan_cache_list_plans.js
1// Test the planCacheListPlans command.2//3// @tags: [4// # This test attempts to perform queries and introspect the server's plan cache entries. The5// # former operation may be routed to a secondary in the replica set, whereas the latter must be6// # routed to the primary.7// # If the balancer is on and chunks are moved, the plan cache can have entries with isActive:8// # false when the test assumes they are true because the query has already been run many times.9// assumes_read_preference_unchanged,10// does_not_support_stepdowns,11// assumes_balancer_off,12// ]13(function() {14 "use strict";15 let t = db.jstests_plan_cache_list_plans;16 t.drop();17 function getPlansForCacheEntry(query, sort, projection) {18 let key = {query: query, sort: sort, projection: projection};19 let res = t.runCommand('planCacheListPlans', key);20 assert.commandWorked(res, 'planCacheListPlans(' + tojson(key, '', true) + ' failed');21 assert(res.hasOwnProperty('plans'),22 'plans missing from planCacheListPlans(' + tojson(key, '', true) + ') result');23 return res;24 }25 // Assert that timeOfCreation exists in the cache entry. The difference between the current time26 // and the time a plan was cached should not be larger than an hour.27 function checkTimeOfCreation(query, sort, projection, date) {28 let key = {query: query, sort: sort, projection: projection};29 let res = t.runCommand('planCacheListPlans', key);30 assert.commandWorked(res, 'planCacheListPlans(' + tojson(key, '', true) + ' failed');31 assert(res.hasOwnProperty('timeOfCreation'),32 'timeOfCreation missing from planCacheListPlans');33 let kMillisecondsPerHour = 1000 * 60 * 60;34 assert.lte(Math.abs(date - res.timeOfCreation.getTime()),35 kMillisecondsPerHour,36 'timeOfCreation value is incorrect');37 }38 assert.commandWorked(t.save({a: 1, b: 1}));39 assert.commandWorked(t.save({a: 1, b: 2}));40 assert.commandWorked(t.save({a: 1, b: 2}));41 assert.commandWorked(t.save({a: 2, b: 2}));42 // We need two indices so that the MultiPlanRunner is executed.43 assert.commandWorked(t.ensureIndex({a: 1}));44 assert.commandWorked(t.ensureIndex({a: 1, b: 1}));45 // Invalid key should be an error.46 assert.eq([],47 getPlansForCacheEntry({unknownfield: 1}, {}, {}).plans,48 'planCacheListPlans should return empty results on unknown query shape');49 // Create a cache entry.50 assert.eq(1,51 t.find({a: 1, b: 1}, {_id: 0, a: 1}).sort({a: -1}).itcount(),52 'unexpected document count');53 let now = (new Date()).getTime();54 checkTimeOfCreation({a: 1, b: 1}, {a: -1}, {_id: 0, a: 1}, now);55 // Retrieve plans for valid cache entry.56 let entry = getPlansForCacheEntry({a: 1, b: 1}, {a: -1}, {_id: 0, a: 1});57 assert(entry.hasOwnProperty('works'),58 'works missing from planCacheListPlans() result ' + tojson(entry));59 assert.eq(entry.isActive, false);60 let plans = entry.plans;61 assert.eq(2, plans.length, 'unexpected number of plans cached for query');62 // Print every plan.63 // Plan details/feedback verified separately in section after Query Plan Revision tests.64 print('planCacheListPlans result:');65 for (let i = 0; i < plans.length; i++) {66 print('plan ' + i + ': ' + tojson(plans[i]));67 }68 // Test the queryHash and planCacheKey property by comparing entries for two different69 // query shapes.70 assert.eq(0, t.find({a: 132}).sort({b: -1, a: 1}).itcount(), 'unexpected document count');71 let entryNewShape = getPlansForCacheEntry({a: 123}, {b: -1, a: 1}, {});72 assert.eq(entry.hasOwnProperty("queryHash"), true);73 assert.eq(entryNewShape.hasOwnProperty("queryHash"), true);74 assert.neq(entry["queryHash"], entryNewShape["queryHash"]);75 assert.eq(entry.hasOwnProperty("planCacheKey"), true);76 assert.eq(entryNewShape.hasOwnProperty("planCacheKey"), true);77 assert.neq(entry["planCacheKey"], entryNewShape["planCacheKey"]);78 //79 // Tests for plan reason and feedback in planCacheListPlans80 //81 // Generate more plans for test query by adding indexes (compound and sparse). This will also82 // clear the plan cache.83 assert.commandWorked(t.ensureIndex({a: -1}, {sparse: true}));84 assert.commandWorked(t.ensureIndex({a: 1, b: 1}));85 // Implementation note: feedback stats is calculated after 20 executions. See86 // PlanCacheEntry::kMaxFeedback.87 let numExecutions = 100;88 for (let i = 0; i < numExecutions; i++) {89 assert.eq(0, t.find({a: 3, b: 3}, {_id: 0, a: 1}).sort({a: -1}).itcount(), 'query failed');90 }91 now = (new Date()).getTime();92 checkTimeOfCreation({a: 3, b: 3}, {a: -1}, {_id: 0, a: 1}, now);93 entry = getPlansForCacheEntry({a: 3, b: 3}, {a: -1}, {_id: 0, a: 1});94 assert(entry.hasOwnProperty('works'), 'works missing from planCacheListPlans() result');95 assert.eq(entry.isActive, true);96 plans = entry.plans;97 // This should be obvious but feedback is available only for the first (winning) plan.98 print('planCacheListPlans result (after adding indexes and completing 20 executions):');99 for (let i = 0; i < plans.length; i++) {100 print('plan ' + i + ': ' + tojson(plans[i]));101 assert.gt(plans[i].reason.score, 0, 'plan ' + i + ' score is invalid');102 if (i > 0) {103 assert.lte(plans[i].reason.score,104 plans[i - 1].reason.score,105 'plans not sorted by score in descending order. ' +106 'plan ' + i +107 ' has a score that is greater than that of the previous plan');108 }109 assert(plans[i].reason.stats.hasOwnProperty('stage'), 'no stats inserted for plan ' + i);110 }...
gasloader.js
Source:gasloader.js
1/**2 * GasLoader3 */4/*5 * The MIT License6 * 7 * Copyright (c) 2011 soundTricker <twitter [at]soundTricker318>8 * 9 * Permission is hereby granted, free of charge, to any person obtaining a copy10 * of this software and associated documentation files (the "Software"), to deal11 * in the Software without restriction, including without limitation the rights12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell13 * copies of the Software, and to permit persons to whom the Software is14 * furnished to do so, subject to the following conditions:15 * 16 * The above copyright notice and this permission notice shall be included in17 * all copies or substantial portions of the Software.18 * 19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN25 * THE SOFTWARE.26*/27(function() {28 var LogLevel = {29 DEBUG : {code : 0 , name : "debug"},30 INFO : {code : 1 , name : "info"},31 ERROR : {code : 2 , name : "error"},32 NONE : {code : 9999 , name : "none"}33 };34 var GasLoaderLogger = this.GasLoaderLogger= function() {35 };36 GasLoaderLogger.prototype = {37 debug : function(message){38 this.log(LogLevel.DEBUG , message);39 },40 info : function(message) {41 this.log(LogLevel.INFO , message);42 },43 error : function(message) {44 this.log(LogLevel.ERROR , message);45 },46 log : function(logLevel , message) {47 if(GasLoader.logLevel.code <= logLevel.code) {48 Logger.log("[GasLoader]["+ logLevel.name +"]" + message);49 }50 }51 52 };53 var GasLoader = this.GasLoader = {54 version : 0.1,55 logLevel : LogLevel.DEBUG,56 loggers : new GasLoaderLogger(),57 defaultCacheSecond : 7 * 24 * 60 * 60,58 cacheKeyPrefix : "GasLoaderCache-",59 cacheListKey : "GasLoaderCacheList" , 60 cache : CacheService.getPublicCache(),61 62 requireFromDocs : function(key, cacheSecond) {63 var scripts = this.getScriptCache_(key);64 if(!scripts) {65 this.loggers.debug("cache is nothing. get from docs " + key);66 scripts = this.getScriptFromDocs_(key);67 this.cache_(key , scripts , cacheSecond);68 }69 70 this.compile(scripts);71 },72 73 require : function(url ,charset, cacheSecond) {74 var scripts = this.getScriptCache_(url);75 if(!scripts) {76 this.loggers.debug("cache is nothing. fetch " + url);77 scripts = this.fetch_(url,charset);78 this.cache_(url , scripts , cacheSecond);79 }80 81 this.compile(scripts);82 },83 84 compile :function(scripts) {85 try {86 var compiledScript = new Script().compile(scripts);87 88 compiledScript();89 90 } catch(e) {91 this.removeCache(url);92 this.loggers.error("throw error at compile script.delete cache. Detail :[" + e + "]");93 throw e;94 }95 },96 97 getScriptFromDocs_ : function(key) {98 var file = DocsList.getFileById(key);99 return file.getContentAsString();100 },101 102 fetch_ : function(url ,charset) {103 var res = UrlFetchApp.fetch(url);104 var scripts = res.getContentText(charset);105 return scripts;106 },107 108 cache_ : function(key , scripts , cacheSecond) {109 var second = cacheSecond || this.defaultCacheSecond;110 if(second > 0) {111 var cacheList = this.getCacheList();112 this.cache.put(this.cacheKeyPrefix + key, scripts,second);113 cacheList.push(key);114 this.cache.put(this.cacheListKey , Utilities.jsonStringify(cacheList));115 this.loggers.info("cached { key:" + this.cacheKeyPrefix + key +" , time: " + second + "}");116 } 117 },118 119 removeCache : function (url) {120 this.cache.remove(this.cacheKeyPrefix + url);121 122 var cacheList = this.getCacheList(this.cache);123 //var cacheList = [];124 cacheList = cacheList.filter(function(obj) {125 return obj != url;126 });127 128 129 this.cache.put(this.cacheListKey, Utilities.jsonStringify(cacheList));130 this.loggers.debug("delete cache. key:" + url);131 },132 133 getScriptCache_ : function(key) {134 return this.cache.get(this.cacheKeyPrefix + key);135 },136 137 getCacheList : function(c) {138 var cache = c || this.cache;139 var cacheListStr = cache.get(this.cacheListKey);140 var cacheList = null;141 if(!cacheListStr) {142 cacheList = [];143 cache.put(this.cacheListKey, Utilities.jsonStringify(cacheList));144 } else {145 cacheList = Utilities.jsonParse(cacheListStr);146 }147 return cacheList;148 }149 };...
plan_cache_list_shapes.js
Source:plan_cache_list_shapes.js
1// Test the planCacheListQueryShapes command, which returns a list of query shapes2// for the queries currently cached in the collection.3//4// @tags: [5// # This test attempts to perform queries with plan cache filters set up. The former operation6// # may be routed to a secondary in the replica set, whereas the latter must be routed to the7// # primary.8// # If all chunks are moved off of a shard, it can cause the plan cache to miss commands.9// assumes_read_preference_unchanged,10// does_not_support_stepdowns,11// assumes_balancer_off,12// ]13(function() {14 const t = db.jstests_plan_cache_list_shapes;15 t.drop();16 // Utility function to list query shapes in cache.17 function getShapes(collection) {18 if (collection === undefined) {19 collection = t;20 }21 const res = collection.runCommand('planCacheListQueryShapes');22 print('planCacheListQueryShapes() = ' + tojson(res));23 assert.commandWorked(res, 'planCacheListQueryShapes failed');24 assert(res.hasOwnProperty('shapes'), 'shapes missing from planCacheListQueryShapes result');25 return res.shapes;26 }27 // Attempting to retrieve cache information on non-existent collection is not an error and28 // should return an empty array of query shapes.29 const missingCollection = db.jstests_query_cache_missing;30 missingCollection.drop();31 assert.eq(0,32 getShapes(missingCollection).length,33 'planCacheListQueryShapes should return empty array on non-existent collection');34 assert.commandWorked(t.save({a: 1, b: 1}));35 assert.commandWorked(t.save({a: 1, b: 2}));36 assert.commandWorked(t.save({a: 1, b: 2}));37 assert.commandWorked(t.save({a: 2, b: 2}));38 // We need two indices so that the MultiPlanRunner is executed.39 assert.commandWorked(t.ensureIndex({a: 1}));40 assert.commandWorked(t.ensureIndex({a: 1, b: 1}));41 // Run a query.42 assert.eq(1,43 t.find({a: 1, b: 1}, {_id: 1, a: 1}).sort({a: -1}).itcount(),44 'unexpected document count');45 // We now expect the two indices to be compared and a cache entry to exist. Retrieve query46 // shapes from the test collection Number of shapes should match queries executed by multi-plan47 // runner.48 let shapes = getShapes();49 assert.eq(1, shapes.length, 'unexpected number of shapes in planCacheListQueryShapes result');50 // Since the queryHash is computed in the server, we filter it out when matching query shapes51 // here.52 let filteredShape0 = shapes[0];53 delete filteredShape0.queryHash;54 assert.eq({query: {a: 1, b: 1}, sort: {a: -1}, projection: {_id: 1, a: 1}},55 filteredShape0,56 'unexpected query shape returned from planCacheListQueryShapes');57 // Running a different query shape should cause another entry to be cached.58 assert.eq(1, t.find({a: 1, b: 1}).itcount(), 'unexpected document count');59 shapes = getShapes();60 assert.eq(2, shapes.length, 'unexpected number of shapes in planCacheListQueryShapes result');61 // Check that each shape has a unique queryHash.62 assert.neq(shapes[0]["queryHash"], shapes[1]["queryHash"]);63 // Check that queries with different regex options have distinct shapes.64 // Insert some documents with strings so we have something to search for.65 for (let i = 0; i < 5; i++) {66 assert.commandWorked(t.insert({a: 3, s: 'hello world'}));67 }68 assert.commandWorked(t.insert({a: 3, s: 'hElLo wOrLd'}));69 // Run a query with a regex. Also must include 'a' so that the query may use more than one70 // index, and thus, must use the MultiPlanner.71 const regexQuery = {s: {$regex: 'hello world', $options: 'm'}, a: 3};72 assert.eq(5, t.find(regexQuery).itcount());73 assert.eq(74 3, getShapes().length, 'unexpected number of shapes in planCacheListQueryShapes result ');75 // Run the same query, but with different regex options. We expect that this should cause a76 // shape to get added.77 regexQuery.s.$options = 'mi';78 // There is one more result since the query is now case sensitive.79 assert.eq(6, t.find(regexQuery).itcount());80 assert.eq(81 4, getShapes().length, 'unexpected number of shapes in planCacheListQueryShapes result');...
plan_cache_list_plans_new_format.js
Source:plan_cache_list_plans_new_format.js
1// Confirms the planCacheListPlans output format.2(function() {3 "use strict";4 const conn = MongoRunner.runMongod();5 assert.neq(null, conn, "mongod was unable to start up");6 const testDB = conn.getDB("jstests_plan_cache_list_plans_new_format");7 const coll = testDB.test;8 assert.commandWorked(9 testDB.adminCommand({setParameter: 1, internalQueryCacheListPlansNewOutput: true}));10 assert.commandWorked(coll.createIndex({a: 1}));11 assert.commandWorked(coll.createIndex({b: 1}));12 const testQuery = {"a": {"$gte": 0}, "b": 32};13 const testSort = {"c": -1};14 const testProjection = {};15 // Validate planCacheListPlans result fields for a query shape with a corresponding cache entry.16 assert.eq(0, coll.find(testQuery).sort(testSort).itcount());17 let key = {query: testQuery, sort: testSort, projection: testProjection};18 let res = assert.commandWorked(coll.runCommand('planCacheListPlans', key));19 // Confirm both the existence and contents of "createdFromQuery".20 assert(res.hasOwnProperty("createdFromQuery"), `planCacheListPlans should return a result with 21 field "createdFromQuery"`);22 assert.eq(res.createdFromQuery.query, testQuery, `createdFromQuery should contain field "query"23 with value ${testQuery}, instead got "createdFromQuery": ${res.createdFromQuery}`);24 assert.eq(res.createdFromQuery.sort, testSort, `createdFromQuery should contain field "sort"25 with value ${testSort}, instead got "createdFromQuery": ${res.createdFromQuery}`);26 assert.eq(res.createdFromQuery.projection, testProjection, `createdFromQuery should contain 27 field "projection" with value ${testProjection}, instead got "createdFromQuery": 28 ${res.createdFromQuery}`);29 // Confirm 'res' contains 'works' and a valid 'queryHash' field.30 assert(res.hasOwnProperty("works"), `planCacheListPlans result is missing "works" field`);31 assert.gt(res.works, 0, `planCacheListPlans result field "works" should be greater than 0`);32 assert(res.hasOwnProperty("queryHash"), `planCacheListPlans result is missing "queryHash" 33 field`);34 assert.eq(8, res.queryHash.length, `planCacheListPlans result field "queryHash" should be 8 35 characters long`);36 // Validate that 'cachedPlan' and 'creationExecStats' fields exist and both have consistent37 // information about the winning plan.38 assert(res.hasOwnProperty("cachedPlan"), `planCacheListPlans result is missing field 39 "cachedPlan" field`);40 assert(res.hasOwnProperty("creationExecStats"), `planCacheListPlans result is missing 41 "creationExecStats" field`);42 assert.gte(res.creationExecStats.length, 2, `creationExecStats should contain stats for both the43 winning plan and all rejected plans. Thus, should contain at least 2 elements but got:44 ${res.creationStats}`);45 let cachedStage = assert(res.cachedPlan.stage, `cachedPlan should have field "stage"`);46 let winningExecStage = assert(res.creationExecStats[0].executionStages, `creationExecStats[0] 47 should have field "executionStages"`);48 assert.eq(cachedStage, winningExecStage, `Information about the winning plan in "cachedPlan" is49 inconsistent with the first element in "creationExecStats".`);50 MongoRunner.stopMongod(conn);...
cache.js
Source:cache.js
1import $router from '@/router/index'2import utils from '@/utils/utils'3let { is } = utils;4export default {5 namespaced: true,6 state: {7 cacheList: ['$root']8 },9 mutations: {10 /*æ·»å ä¸ä¸ªé¡µé¢å°ç¼åä¸ */11 addCache(state, value) {12 if (state.cacheList.indexOf(value) == -1) {13 state.cacheList.push(value);14 }15 },16 /**å é¤æå®ç¼å */17 removeCache(state, value) {18 if (state.cacheList.indexOf(value) !== -1) {19 let index = state.cacheList.indexOf(value);20 state.cacheList.splice(index, 1);21 }22 },23 /**å·æ°æå®ç¼å */24 refresh(state, value) {25 if (!value) {26 state.cacheList = ['$root'];27 setTimeout(() => {28 state.cacheList = ['$root'].concat(initCache());29 });30 return;31 }32 let index = state.cacheList.indexOf(value);33 if (index !== -1) {34 state.cacheList.splice(index, 1);35 setTimeout(() => {36 state.cacheList.push(value);37 });38 }39 },40 /**ä¸å·æ°æå®ç¼å */41 notRefresh(state, value){42 state.cacheList = ['$root',value];43 setTimeout(() => {44 state.cacheList = ['$root'].concat(initCache());45 });46 },47 /**å é¤é¡µé¢ç¼å */48 clearCache(state, value) {49 state.cacheList = ['$root'];50 },51 /**åå§åç¼å */52 initCache(state, value) {53 state.cacheList = ['$root'].concat(initCache());54 }55 }56}57function initCache() {58 let { routes } = $router.options;59 let names = [];60 getCache(routes, names)61 return names;62}63function getCache(routes, result) {64 if (!is().Array(routes)) {65 return;66 }67 if (routes.length == 0) {68 return;69 }70 for (let i = 0; i < routes.length; i++) {71 let route = routes[i];72 if (route.meta && route.meta.keepAlive) {73 result.push(route.name);74 }75 getCache(route.children, result)76 }...
cache.list.custom.js
Source:cache.list.custom.js
1var f = function(){2 var _ = NEJ.P,3 _f = NEJ.F,4 _u = _('nej.u'),5 _e = _('nej.e'),6 _p = _('nej.ut'),7 _j = _('nej.j'),8 _proCacheListCustom,9 _supCacheListCustom;10 _p._$$CacheListCustom = NEJ.C();11 _proCacheListCustom = _p._$$CacheListCustom._$extend(_p._$$AbstractListCache);12 _supCacheListCustom = _proCacheListCustom._$supro;13 14 _proCacheListCustom.__doLoadList = function(_options){15 var _key = _options.key;16 var _data = _options.data;17 var _offset = _options.offset;18 var _limit = _options.limit;19 var _rkey = _options.rkey;20 var _onload = _options.onload;21 _j._$request('http://123.163.com:3000/xhr/getLog',{22 type:'json',23 method:'POST',24 data:{offset:_offset,limit:_limit},25 timeout:1000,26 onload:_onload._$bind(this),27 onerror:function(_error){}28 }29 );30 };31 32 _proCacheListCustom.__doLoadItem = function(_options){33 var _id = _options.id;34 var _key = _options.key;35 var _rkey = _options.rkey;36 var _onload = _options.onload;37 _j._$request('http://123.163.com:3000/xhr/getLog',{38 type:'json',39 method:'POST',40 data:{rkey:_rkey},41 timeout:1000,42 onload:_onload._$bind(this),43 onerror:function(_error){}44 }45 );46 };47 48 // todo49 _proCacheListCustom.__doAddItem = function(){50 51 };52 53 // todo54 _proCacheListCustom.__doDeleteItem = function(){55 56 };57 58 // todo59 _proCacheListCustom.__doUpdateItem = function(){60 61 };62 63}64define('{pro}util/cache.list.custom.js',['{lib}util/cache/cache.list.base.js'],f);
...
list.test.js
Source:list.test.js
1// @flow2import { cacheList, toCacheListOptions } from '../list';3import * as yarn from '../../../utils/yarn';4jest.mock('../../../utils/yarn');5describe('bolt cache list', () => {6 it('should handle situation where no arguments are passed', async () => {7 await cacheList(8 toCacheListOptions([], {9 cwd: 'dummyPattern/dummyPath'10 })11 );12 expect(13 yarn.cliCommand14 ).toHaveBeenCalledWith('dummyPattern/dummyPath', 'cache', ['list']);15 });16 it('should handle --pattern flag', async () => {17 await cacheList(18 toCacheListOptions([], {19 cwd: 'dummyPattern/dummyPath',20 pattern: 'jest'21 })22 );23 expect(24 yarn.cliCommand25 ).toHaveBeenCalledWith('dummyPattern/dummyPath', 'cache', [26 'list',27 '--pattern=jest'28 ]);29 });...
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.get('input[name="q"]').type('cypress')4 cy.get('input[name="btnK"]').click()5 cy.wait(2000)6 cy.get('div.g').then(els => {7 const cached = Cypress.dom.cache.list()8 expect(cached).to.include(first)9 })10 })11})
Using AI Code Generation
1describe('Test', () => {2 it('test', () => {3 cy.wait(5000)4 cy.wait(5000)5 cy.wait(5000)6 cy.wait(5000)7 cy.wait(5000)8 cy.wait(5000)9 cy.wait(5000)10 cy.wait(5000)11 cy.wait(5000)12 cy.wait(5000)13 cy.wait(5000)14 cy.wait(5000)15 cy.wait(5000)16 cy.wait(5000)17 cy.wait(5000)18 cy.wait(5000)19 cy.wait(5000)20 cy.wait(5000)21 cy.wait(5000)22 cy.wait(5000)23 cy.wait(5000)24 cy.wait(5000)25 cy.wait(5000)26 cy.wait(5000)27 cy.wait(5000)28 cy.wait(5000)29 cy.wait(5000)30 cy.wait(5000
Using AI Code Generation
1describe('Test to verify cache.list method of Cypress', function() {2 it('Test to verify cache.list method of Cypress', function() {3 cy.clearLocalStorage()4 cy.clearCookies()5 cy.clearLocalStorageSnapshot()6 cy.clearLocalStorageCache()7 cy.clearLocalStorageCache()
Using AI Code Generation
1Cypress.on('window:before:load', window => {2 Object.defineProperty(window, 'list', {3 get: () => {4 return () => {5 return window.Cypress._.keys(window.__cypress_webpack_preprocessor_cache__)6 }7 }8 })9})10it('should work', () => {11 cy.window().then(win => {12 })13})14If you want to use a different proxy server, you'll need to configure it to cache files and serve them to Cypress. The important thing is that it needs to:
Using AI Code Generation
1describe('Cypress Cache API', function() {2 it('lists cache', function() {3 cy.get('#clear-local-storage').click()4 cy.get('#set-item').click()5 cy.get('#your-item').should('have.text', 'foo: bar')6 cy.window().then(win => {7 cy.wrap(win.localStorage.getItem('foo')).should('equal', 'bar')8 })9 cy.get('#get-item').click()10 cy.get('#your-item').should('have.text', 'foo: bar')11 })12})13const cache = require('cypress-plugin-tab')14module.exports = (on, config) => {15 on('task', {16 })17}18const cache = require('cypress-plugin-tab')19Cypress.Commands.add('cache', cache)
Using AI Code Generation
1describe('Cypress Cache', () => {2 it('should list the cache', () => {3 cy.log('List the cache')4 cy.cacheList()5 })6})7Cypress.Commands.add('cacheList', () => {8 cy.window().then(win => {9 win.caches.open('cypress-cache').then(cache => {10 cache.keys().then(keys => {11 keys.forEach(key => {12 cache.match(key).then(response => {13 response.text().then(text => {14 cy.log(`${key.url}: ${text}`)15 })16 })17 })18 })19 })20 })21})22cy.cacheClear()23cy.cacheList()
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!