/******************************************************************************* * * Nx本地缓存管理 * * * * 2021.12.10 ******************************************************************************/ const CFG = require( "config" ); const NxObject = require( "nx.object" ); const Crypto = require( "cryptoHelper" ); const nxStorage = cc.Class( { extends: NxObject, name: "nxStorage", sd: null, // 初始化 initialize: function( _args ) { // USPER this._super( _args ); this.sd = cc.sys.localStorage; nx.storage = this; return true; }, // 销毁 uninitialize: function() { nx.storage = null; // USPER return this._super(); }, // 取值 get: function( _key, _def = "", _pri = false ) { if( nx.dt.strEmpty( _key ) ) { nx.logger.error( "[缓存]空键值" ); return _def; } let val = this.sd.getItem( this.skey( _key, _pri ) ); return Crypto.decrypt( val ) || _def; }, // 取数 getNumber: function( _key, _def = 0, _pri = false ) { let val = this.get( _key, _def, _pri ); let num = parseInt( val ); if( !nx.dt.numGood( num ) ) { num = _def; } return num; }, // 取对象 getObject: function( key, _pri ) { return JSON.parse( this.get( key, "{}", _pri ) ); }, // 设值 set: function( _key, _value, _pri ) { if( nx.dt.strEmpty( _key ) ) { nx.logger.error( "[缓存]空键值" ); return; } let val = Crypto.encrypt( "" + _value ); this.sd.setItem( this.skey( _key, _pri ), val ); nx.logger.debug( "[缓存]更新:%s -> %s", _key, _value ); }, // 设对象 setObject: function( key, value, _pri ) { this.set( key, JSON.stringify( value ), _pri ); }, // 删值 del: function( _key, _pri ) { if( nx.dt.strEmpty( _key ) ) { nx.logger.warn( "[缓存]空键值" ); return; } this.sd.removeItem( this.skey( _key, _pri ) ); nx.logger.debug( "[缓存]删除:%s", _key ); }, // 关键字组合 skey: function( _key, _pri ) { // 是否私有 if( _pri ) { let info = nx.bridge.vget( "curRole" ); if( info ) { _key = nx.text.format( "%s.%s.%s", _key, info.srv_id, info.rid ); } } return cc.js.formatStr( "[%s]%s", this.prefix(), _key ); }, // 获取唯一前缀 prefix: function() { let key = CFG.GName; if( window.nx && nx.frame ) { key = nx.frame.vget( "GUUID" ); } return key || CFG.GName; }, } ); // 模块导出 module.exports = nxStorage;