cache.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. type Timer = ReturnType<typeof setTimeout>;
  2. type CachedKey = string | number;
  3. export interface CachedData<TData = any, TParams = any> {
  4. data: TData;
  5. params: TParams;
  6. time: number;
  7. }
  8. interface RecordData extends CachedData {
  9. timer: Timer | undefined;
  10. }
  11. const cache = new Map<CachedKey, RecordData>();
  12. export const setCache = (key: CachedKey, cacheTime: number, cachedData: CachedData) => {
  13. const currentCache = cache.get(key);
  14. if (currentCache?.timer) {
  15. clearTimeout(currentCache.timer);
  16. }
  17. let timer: Timer | undefined = undefined;
  18. if (cacheTime > -1) {
  19. // if cache out, clear it
  20. timer = setTimeout(() => {
  21. cache.delete(key);
  22. }, cacheTime);
  23. }
  24. cache.set(key, {
  25. ...cachedData,
  26. timer,
  27. });
  28. };
  29. export const getCache = (key: CachedKey) => {
  30. return cache.get(key);
  31. };
  32. export const clearCache = (key?: string | string[]) => {
  33. if (key) {
  34. const cacheKeys = Array.isArray(key) ? key : [key];
  35. cacheKeys.forEach((cacheKey) => cache.delete(cacheKey));
  36. } else {
  37. cache.clear();
  38. }
  39. };