axios请求缓存+防止重复提交
分类专栏: Javascript&
简介 前端实现api接口缓存。
<pre>import axios from 'axios'
// 数据存储
export const cache = {
data: {},
set (key, data) {
this.data[key] = data
},
get (key) {
return this.data[key]
},
clear (key) {
delete this.data[key]
}
}
// 建立唯一的key值
export const buildUniqueUrl = (url, method, params = {}, data = {}) => {
const paramStr = (obj) => {
if (toString.call(obj) === '[object Object]') {
return JSON.stringify(Object.keys(obj).sort().reduce((result, key) => {
result[key] = obj[key]
return result
}, {}))
} else {
return JSON.stringify(obj)
}
}
url += `?${paramStr(params)}&${paramStr(data)}&${method}`
return url
}
// 防止重复请求
export default (options = {}) => async config => {
const defaultOptions = {
time: 0, // 设置为0,不清除缓存
...options
}
const index = buildUniqueUrl(config.url,config.method,config.params,config.data)
let responsePromise = cache.get(index)
if (!responsePromise) {
responsePromise = (async () => {
try {
const response = await axios.defaults.adapter(config)
return Promise.resolve(response)
} catch (reason) {
cache.clear(index)
return Promise.reject(reason)
}
})()
cache.set(index, responsePromise)
if (defaultOptions.time !== 0) {
setTimeout(() => {
cache.clear(index)
}, defaultOptions.time)
}
}
return responsePromise.then(data => JSON.parse(JSON.stringify(data))) // 为防止数据源污染
}
例子:
import axios from 'axios'
import cache from './cache'
// get请求
export async function getData (payload) {
return axios.get('/path', {
params: payload,
adapter: cache({
time: 0
})
})
}
// post请求
export async function postData (payload) {
return axios.post('/path', payload, {
adapter: cache({
time: 1000
})
})
}
</pre>
分享到:
转载:
https://segmentfault.com/a/1190000013167994
喜欢 1
收藏
暂无评论信息
- 相关文章
- 文章推荐
-
娱美德旗下MMORPG手游《传奇4》将推出新PVP玩法"比奇掠夺"&
《传奇4》推出新门派PVP玩法!韩国首尔2022年6月29日 /美通社/ -- 《传奇4》(MIR4)的新PVP玩法比奇掠夺(Bicheon Heist)于2022年6月28日推出。
-
半导体短缺即将结束?分析师:如果没有 1 美元芯片会影响更多
德勤咨询(Deloitte Consulting)的芯片分析师认为,随着芯片行业资本支出的增加,需求度较高的工厂已经开工,预示着短缺情况即将结束。
-
HTML 面试知识点总结
本部分主要是笔者在复习 HTML 相关知识和一些相关面试题时所做的笔记,如果出现错误,希望大家指出!
-
亚马逊推出“无需收银员”的新技术,以此帮助品牌和广告商提高销量
北京时间 6 月 30 日早间消息,据报道,亚马逊发明了一种无需收银员的技术,可以加快人们去杂货店或便利店的速度。现在,该公司希望利用这个跟踪系统来帮助品牌和广告商提高销量。&
- 点击排行
- 站长推荐
- 猜你喜欢
- 网站信息
- 站内问答:12篇
- 站内文章:213篇
- 建站时间:已运行1244天
- 备案号: 浙ICP备2022018799号
- 语言:
- English(USA)
- French(FR)
- Chinese(ZH)
无数据