eventStore.tsx 2.0 KB

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