cache.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. // @ts-ignore
  2. import md5 from '../../encryption/md5';
  3. import storage from "$utils/tool/storage";
  4. import { InstructionsCacheType } from '$utils/request/const/request';
  5. export default class Cache {
  6. static key:string='cache:'
  7. // 缓存的数据
  8. caches:Record<string, InstructionsCache> = {};
  9. static sign(requestData:LibRequestOptions) {
  10. let keys = Object.keys(requestData.data || {}).sort();
  11. let sign:string = '';
  12. // 执行 建立 数据记录 合集
  13. for (let i = 0, count = keys.length; i < count; i++) {
  14. // @ts-ignore
  15. let value = requestData.data[keys[i]];
  16. if (value === undefined) value = '';
  17. sign += keys[i]+':'+value;
  18. }
  19. // 构造唯一值
  20. // @ts-ignore
  21. return md5(requestData.url +'-'+ sign);
  22. }
  23. // 获取缓存
  24. getCache(sign:string,expire:boolean = true):InstructionsCache | undefined{
  25. // 查看内存是否存在且可以使用
  26. if (this.caches[sign]) {
  27. if (expire && Cache.isExpire(this.caches[sign])) {
  28. return this.caches[sign];
  29. } else {
  30. return this.caches[sign];
  31. }
  32. }
  33. // 否则查询缓存
  34. else {
  35. let data:InstructionsCache = storage.getItem(Cache.key+':'+sign);
  36. if (data) {
  37. data.first = undefined;
  38. return this.setCache(sign,data);
  39. }
  40. }
  41. return undefined;
  42. }
  43. // 设置缓存
  44. setCache(sign:string,cache:InstructionsCache):InstructionsCache{
  45. let resultCache:InstructionsCache;
  46. if (typeof cache === 'boolean') {
  47. resultCache = {};
  48. } else {
  49. resultCache = {...cache};
  50. }
  51. resultCache.expireTime = resultCache.expireTime || 0;
  52. // 设置过期时间
  53. resultCache.expireTime = !resultCache.expireTime || resultCache.expireTime<=0 ? resultCache.expireTime : Cache.getNowTime() + resultCache.expireTime;
  54. if (this.caches[sign]) {
  55. resultCache.first = this.caches[sign].first;
  56. }
  57. // 设置是否为第一次
  58. resultCache.first = resultCache.first === undefined;
  59. this.caches[sign] = resultCache;
  60. // 设置缓存
  61. if (
  62. resultCache.type === undefined || resultCache.type === InstructionsCacheType.storage
  63. ) {
  64. if (resultCache.expireTime != null) {
  65. storage.setItem(Cache.key + ':' + sign, resultCache, resultCache.expireTime);
  66. }
  67. }
  68. return resultCache;
  69. }
  70. // 验证是否过期
  71. static isExpire(data:InstructionsCache):boolean {
  72. return !data.expireTime || data.expireTime <=0 || Cache.getNowTime() < data.expireTime;
  73. }
  74. // 获取当前时间
  75. static getNowTime(){
  76. return parseInt((new Date().getTime() / 1000).toString());
  77. }
  78. }