前端代码设计之优雅的缓存Axios请求结果

开始设计

作为8年前端的我,在设计代码之前,我比较喜欢先想好怎么用,然后再去实现。想来想去,我觉得像先下面这样使用会比较好一些:

针对某个接口开启结果缓存

export function fetchList () {
return request.cache('缓存key').get('/myinterface')
}

调用接口的时候指定先从缓存中获取

fetchList()
.cache() // 如果某情况需要强制调用接口来获取,则去掉该方法即可。
.then(data => {})
.catch(e => {})
.finally(() => {})

WHY?

为什么这么使用?

  • 在接口调用方面,可以满足从缓存中获取和强制从接口中获取两种情况,这样使用起来会比较灵活一些。
  • 在接口定义方面,我们一定需要一个缓存键。但这个缓存键为什么不能直接默认使用接口参数?因为接口可能无需参数,那为什么不能直接默认使用接口地址?因为restful风格下接口是一样的,只是请求方式不一样。那为什么不能直接使用接口+参数,这就考验设计者对设计的觉悟了。从设计角度来讲,接口地址加参数的确可以标识唯一,但存在不可预见性,所以也不建议这么做。

代码实现

我不能说代码很简单,虽然代码量不大,但的确需要理一下。

// 缓存请求结果
const buildCachePromise = (cacheKey, method, args, cacheImpl) => {
return {
__cacheImpl: cache[cacheImpl],
__arguments: args,
__result_promise: null,
// 开启缓存
cache () {
const data = this.__cacheImpl.getJSON(cacheKey)
if (data != null) {
this.__result_promise = Promise.resolve(data)
}
if (this.__result_promise != null) {
return this.__result_promise
}
return this
},
then () {
return this.__access('then', arguments)
},
catch () {
return this.__access('catch', arguments)
},
finally () {
return this.__access('finally', arguments)
},
__access (methodName, args) {
if (this.__result_promise != null) {
return this.__result_promise
}
this.__result_promise = axiosInstance[method].apply(axiosInstance, this.__arguments)
this.__result_promise.then(data => {
this.__cacheImpl.setJSON(cacheKey, data)
return data
})
return this.__result_promise[methodName].apply(this.__result_promise, args)
}
}
}
const methods = ['get', 'post', 'delete', 'put', 'head', 'options', 'patch', 'request']
axiosInstance.cache = function (cacheKey, isLocal = false) {
if (cacheKey == null) {
throw Error('Request cache key can not be null.')
}
const cacheAxiosInstance = {}
for (const method of methods) {
cacheAxiosInstance[method] = function () {
return buildCachePromise(cacheKey, method, arguments, isLocal ? 'local' : 'session')
}
}
return cacheAxiosInstance
}

代码虽然说是我自己写的,但是,我不得不说我自己再看一遍,我还是得理一理。不过不重要,好用就行!这套代码是从我的开源框架Eva中提取出来的。后面还会跟大家介绍更多代码设计方面的内容。

Eva开源框架的主要目的呢,是能够进行快速开发项目,并且还能养成一套良好的开发规范,对于新手而言呢,也要做到是一套好的学习项目。

  • Eva开源框架GITEE:gitee.com/coderd-repo…[1]
  • Eva开源框架GITHUB:github.com/coderd-repo…[2]

欢迎star!

关注我!和你一起探讨代码设计的艺术。

参考资料

[1]

https://gitee.com/coderd-repos/eva: https://gitee.com/coderd-repos/eva

[2]

https://github.com/coderd-repos/eva: https://github.com/coderd-repos/eva


原文始发于微信公众号(消失的程序员):前端代码设计之优雅的缓存Axios请求结果

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/272630.html

(0)
木子先生的头像木子先生

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!