js接口逻辑设计

53 阅读1分钟

记录一个存取功能具体(简单)实现的设计

  • 实现一个具体类,按照具体功能分类为不同的层,内部实现可以复杂,但必须方便使用者使用,以下简单实现了设计结构,
    • 根据传入的不同配置,在能力层增加根据配置判断是否使用不同的数据处理逻辑
    • 根据传入配置,决定存储取出的存储仓
    • 根据具体需求功能,暴露对应API供于外部使用

设计分层.jpg

结构图.jpg

//模拟浏览器window对象
const window={
    localStorage:{
        setItem(){
            //...
        }
    }
}
class CreateStore{
    constructor(opts={}){
        this.initOpts(opts)
        this.observe()
    }
    un_local=false;
    should_fetch=false;
    max_length=2;
    expire_item=Infinity;
    plugins=[];
    now=new Date().getTime();

    initOpts(opts){
       
        const {
            un_local,
            should_fetch,
            max_length,
            expire_item,
            storage_method='localStorage',
            plugins=[],
        }=opts
      
        this.un_local=Boolean(un_local);
        this.should_fetch=Boolean(should_fetch);
        this.max_length=Number(max_length||30);
        this.expire_item=Boolean(expire_item||Infinity);
        this.plugins=plugins||[];
        this.now=new Date();
      
        this.storage_method=storage_method;
        this.__mock__storage=null;
    }

    get (key){
        
        return this.__mock__storage[key]
    }
    set(key,data){
        return this.__mock__storage[`${key}`]=data;
    }

    observe(){
        const that=this;
        this.__mock__storage= new Proxy({},{
            get(target,propKey,receiver){
                let result;
                if(that.un_local){
                    result = Reflect.get(target,propKey,receiver)
                }
                else{
                    result=that.getItem(propKey) || Reflect.get(target,propKey,receiver);
                }
                return result;
            },
            set(target,propKey,value,receiver){
                //存入数据的时候做能力层处理
                let __value__=value;
                if(Array.isArray(value)&&value.lenght>that.max_length){
                    __value__=value.slice(0,that.max_length)
                }
                if(that.expire_item && this.expire_item + that.now() < Data.now()){
                  // 清除失效数据
                }
                
                //存储层判断
                if(!that.un_local){
                    that.setItem(propKey,__value__)
                }
                else if(should_fetch){
                    //是否服务端存储...
                }
                return Reflect.set(target,propKey,__value__,receiver)

            }
        })
    }
    getItem(type){
        let data;
        try{
            data =window[this.storage_method].getItem(type)
        }
        catch(e){
            
        }
        let dataJson
        try{
            dataJson=JSON.parse(data)
        }
        catch(e){
            
         }
         return dataJson;
    }

    setItem(type,data){
        let dataJson=JSON.stringify(data);
        try{
            
            window[this.storage_method].setItem(dataJson)
        }
        catch(e){
            console.log('error',e)
        }
    }

}

//能力扩展
const methods=['pop','push','shift','unshift','splice','reverse','sort','copyWithin']
methods.forEach(method=>{
    CreateStore.prototype[method]=function(type,...args){
       if(!this.get(type)){
            this.set(type,[])
       }

       if(this.get(type) instanceof Array){
            const dataList=this.get(type)
            Array.prototype[method].apply(dataList,args);
            this.set(type,dataList);
       }
       else{
            throw new RTCError('data type is not array');
       }
    }
})

const localStore=new CreateStore({storage_method:'localStorage'});
localStore.set('hi',['1234567890']);
localStore.push('hi','12345678901');

console.log('log=>localStore:',localStore.get('hi'));