apiServiceCache.js 2.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
/**
 * 将接口数据进行缓存, 节流接口让页面没有那么卡顿
 * 钟是志
 * 2022年12月8日
 * */

window.onestopApiServiceCacheData = {};

const cacheApiconfig = [
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
	{
		key: 'findParamsKey', // 接口唯一的键
		url: '/SqlManageEntityApi/findParamsKey', // 接口地址
		searchParams: 'sqlKey', // 缓存的参数
		time: 600, // 缓存数据有效期.  单位秒
	},
	{
		key: 'find', // 接口唯一的键
		url: '/SqlManageEntityApi/find', // 接口地址
		searchParams: 'sqlKey', // 缓存的参数
		time: 600, // 缓存数据有效期.  单位秒
	},
	{
		key: 'getSqlOptions', // 接口唯一的键
		url: '/DataColumnApi/getSqlOptions', // 接口地址
		searchParams: 'sqlKey', // 缓存的参数
		otherParams: 'allValues',
		time: 1, // 缓存数据有效期.  单位秒
	},
29 30 31 32 33 34 35 36
  {
    key: 'getSqlData', // 接口唯一的键
    url: '/DataColumnApi/getSqlData', // 接口地址
    searchParams: 'sqlKey', // 缓存的参数
    // otherParams: 'allValues',
    time: 600, // 缓存数据有效期.  单位秒
    isCache: true,
  },
37 38
];

39
function getConfig(apiUrl, params) {
40
	let findConfig = cacheApiconfig.find((g) => {
41 42 43 44 45 46 47 48 49 50 51
	  if(apiUrl === g.url){
	    if(g.isCache){
	      if(params.isCache){
	        return true;
        }else{
	        return false;
        }
      }
	    return true;
    }
	  return  false;
52 53
	});
	return findConfig || undefined;
54 55 56
}

// 获取缓存数据
57 58
export function getCacheData(apiUrl, params) {
	return new Promise((resolve, reject) => {
59
		let findConfig = getConfig(apiUrl, params);
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
		if (!findConfig) {
			resolve(false);
			return;
		}
		let res = window.onestopApiServiceCacheData[findConfig.key + params[findConfig.searchParams]];
		if (!res ||
      new Date().getTime() > res?.expiresTime ||
      (params[findConfig.otherParams] && params[findConfig.otherParams] !== res.otherParams)
    ) {
			window.onestopApiServiceCacheData[findConfig.key + params[findConfig.searchParams]] =
				'pending';
			resolve(false);
			return;
		}
		if (res === 'pending') {
			let interval = setInterval(() => {
				let newD =
					window.onestopApiServiceCacheData[findConfig.key + params[findConfig.searchParams]];
				if (newD !== 'pending') {
					clearInterval(interval);
					resolve(newD.response);
					return newD.response;
				}
			}, 200);
		} else {
			resolve(res.response);
			return res.response;
		}
	});
89 90 91
}

// 保存缓存数据
92
export function saveCacheData(apiUrl = '', params, response = {}) {
93
	let findConfig = getConfig(apiUrl, params);
94 95 96 97 98 99 100 101 102 103 104 105
	if (findConfig) {
		// console.log(params);
		window.onestopApiServiceCacheData[findConfig.key + params[findConfig.searchParams]] = {
			response,
			expiresTime: new Date().getTime() + findConfig.time * 1000,
			otherParams: params[findConfig.otherParams] || undefined, // 接口参数做缓存
		};
		// console.log(window.onestopApiServiceCacheData);
		return true;
	} else {
		return false;
	}
106
}