如何解决支持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 举报,一经查实,本站将立刻删除。