支持Rest API的Javascript数据模型

问题描述

我一直在努力寻找一种用javascript定义此方法的好方法,说实话,我有点碰壁。我不认为这总体上很复杂,但是,寻求有关如何最好地解决问题的灵感或指导。

我正在构建一个Web应用程序,并且自然而然地将其与可与json负载一起使用的rest api集成在一起。通常,当我实现此功能时,我只会使用axios或fetch之类的东西,进行调用并直接使用json响应。

我想要创建的东西更类似于商店和模型,提供诸如find,findById,便捷方法之类的方法

此伪代码内容

   //Store handles the API methods,probably returns promise or something and returns the Customer
   const CustomerStore = {

       findById = (id) = > {
          let _customer = {};            
          axios.get('url/:id')
             .then( (data) => { _customer = new Customer(data) )
             .then( return _customer);
          
       }
        
       //saves (creates or updates based on id value) the customer
       save = (customer) => {
       
       }

       //deletes a customer
       delete = (id) => {

       }
    
   }


    //The customer model,just represents a customer 
    //Not sure this should have convienence methods like save() or something that calls the store.
    const Customer = {
      id,firstName,lastName,name = () => {
       return `${lastName},${firstName}`;
      }
    
    }

   

  const someImplementation = {

     let aCustomer = CustomerStore.findById(10).then( (customer) => setState({customer: customer})

  }

理想地,find / lookup方法将解析响应并返回一个新的Customer实例,如果有多个,则返回一个Customer实例的集合。我不确定是否应该使用这些与客户模型一起使用的方法来拥有一个CustomerStore,这可能是有道理的。我确实看到CustomerStore是单身人士。

计划是将其打包为一个npm软件包(即customer-api),这样我就可以通过依赖项将其导入到我的项目中,并且可以在任何地方使用我的标准api。我将在每个模型中实施特定的逻辑,以便到处都有一致的方法来说出客户的全名或地址等。

tldr;并不是寻找完整的解决方案,可能只是一些有关在javascript中实现商店/模型的良好策略的指导或想法。我希望在内部进行构建。

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)