eventStore.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import extend from 'lodash/extend';
  2. import isArray from 'lodash/isArray';
  3. import {createStore, StoreDefinition} from 'reflux';
  4. import {Event} from 'sentry/types/event';
  5. import {makeSafeRefluxStore} from 'sentry/utils/makeSafeRefluxStore';
  6. type InternalDefinition = {
  7. items: Event[];
  8. itemsById: Record<string, Event>;
  9. };
  10. interface EventStoreDefinition extends StoreDefinition, InternalDefinition {
  11. add(items: Event[]): void;
  12. get(id: string): Event | undefined;
  13. getAllItemIds(): string[];
  14. getAllItems(): Event[];
  15. init(): void;
  16. loadInitialData(items: Event[]): void;
  17. remove(id: string): void;
  18. reset(): void;
  19. }
  20. const storeConfig: EventStoreDefinition = {
  21. items: [],
  22. itemsById: {},
  23. init() {
  24. this.reset();
  25. },
  26. reset() {
  27. this.items = [];
  28. },
  29. loadInitialData(items) {
  30. this.reset();
  31. const itemIds = new Set();
  32. items.forEach(item => {
  33. itemIds.add(item.id);
  34. this.items.push(item);
  35. });
  36. this.trigger(itemIds);
  37. },
  38. add(items) {
  39. if (!isArray(items)) {
  40. items = [items];
  41. }
  42. const itemsById = {};
  43. const itemIds = new Set();
  44. items.forEach(item => {
  45. itemsById[item.id] = item;
  46. itemIds.add(item.id);
  47. });
  48. items.forEach((item, idx) => {
  49. if (itemsById[item.id]) {
  50. this.items[idx] = extend(true, {}, item, itemsById[item.id]);
  51. delete itemsById[item.id];
  52. }
  53. });
  54. for (const itemId in itemsById) {
  55. this.items.push(itemsById[itemId]);
  56. }
  57. this.trigger(itemIds);
  58. },
  59. remove(itemId) {
  60. this.items.forEach((item, idx) => {
  61. if (item.id === itemId) {
  62. this.items.splice(idx, idx + 1);
  63. }
  64. });
  65. this.trigger(new Set([itemId]));
  66. },
  67. get(id) {
  68. for (let i = 0; i < this.items.length; i++) {
  69. if (this.items[i].id === id) {
  70. return this.items[i];
  71. }
  72. }
  73. return undefined;
  74. },
  75. getAllItemIds() {
  76. return this.items.map(item => item.id);
  77. },
  78. getAllItems() {
  79. return this.items;
  80. },
  81. };
  82. const EventStore = createStore(makeSafeRefluxStore(storeConfig));
  83. export default EventStore;