IssueListCacheStore.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import isEqual from 'lodash/isEqual';
  2. import {createStore} from 'reflux';
  3. import type {Group} from 'sentry/types';
  4. import {CommonStoreDefinition} from './types';
  5. /**
  6. * The type here doesn't really matter it just needs to be compared via isEqual
  7. */
  8. type LooseParamsType = Record<string, any>;
  9. interface IssueListCache {
  10. groups: Group[];
  11. pageLinks: string;
  12. queryCount: number;
  13. queryMaxCount: number;
  14. }
  15. interface IssueListCacheState {
  16. /**
  17. * The data that was cached
  18. */
  19. cache: IssueListCache;
  20. /**
  21. * Do not use this directly, use `getFromCache` instead
  22. */
  23. expiration: number;
  24. /**
  25. * The params that were used to generate the cache
  26. * eg - {query: 'Some query'}
  27. */
  28. params: LooseParamsType;
  29. }
  30. interface InternalDefinition {
  31. state: IssueListCacheState | null;
  32. }
  33. // 30 seconds
  34. const CACHE_EXPIRATION = 30 * 1000;
  35. interface IssueListCacheStoreDefinition
  36. extends CommonStoreDefinition<IssueListCache | null>,
  37. InternalDefinition {
  38. getFromCache(params: LooseParamsType): IssueListCache | null;
  39. reset(): void;
  40. save(params: LooseParamsType, data: IssueListCache): void;
  41. }
  42. const storeConfig: IssueListCacheStoreDefinition = {
  43. state: null,
  44. init() {},
  45. reset() {
  46. this.state = null;
  47. },
  48. save(params: LooseParamsType, data: IssueListCache) {
  49. this.state = {
  50. params,
  51. cache: data,
  52. expiration: Date.now() + CACHE_EXPIRATION,
  53. };
  54. },
  55. getFromCache(params: LooseParamsType) {
  56. if (
  57. this.state &&
  58. this.state.expiration > Date.now() &&
  59. isEqual(this.state?.params, params)
  60. ) {
  61. return this.state.cache;
  62. }
  63. return null;
  64. },
  65. getState() {
  66. return this.state?.cache ?? null;
  67. },
  68. };
  69. const IssueListCacheStore = createStore(storeConfig);
  70. export default IssueListCacheStore;