How to use cache.list method in Cypress

Best JavaScript code snippet using cypress

list.js

Source:list.js Github

copy

Full Screen

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;...

Full Screen

Full Screen

plan_cache_list_plans.js

Source:plan_cache_list_plans.js Github

copy

Full Screen

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    }...

Full Screen

Full Screen

gasloader.js

Source:gasloader.js Github

copy

Full Screen

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  };...

Full Screen

Full Screen

plan_cache_list_shapes.js

Source:plan_cache_list_shapes.js Github

copy

Full Screen

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');...

Full Screen

Full Screen

plan_cache_list_plans_new_format.js

Source:plan_cache_list_plans_new_format.js Github

copy

Full Screen

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);...

Full Screen

Full Screen

cache.js

Source:cache.js Github

copy

Full Screen

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    }...

Full Screen

Full Screen

cache.list.custom.js

Source:cache.list.custom.js Github

copy

Full Screen

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);
...

Full Screen

Full Screen

list.test.js

Source:list.test.js Github

copy

Full Screen

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  });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

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})

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

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()

Full Screen

Using AI Code Generation

copy

Full Screen

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:

Full Screen

Using AI Code Generation

copy

Full Screen

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)

Full Screen

Using AI Code Generation

copy

Full Screen

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()

Full Screen

Cypress Tutorial

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.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

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.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful