organizationsStore.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import {createStore, StoreDefinition} from 'reflux';
  2. import {Organization} from 'sentry/types';
  3. interface OrganizationsStoreDefinition extends StoreDefinition {
  4. addOrReplace(item: Organization): void;
  5. get(slug: string): Organization | undefined;
  6. getAll(): Organization[];
  7. getState(): Organization[];
  8. load(items: Organization[]): void;
  9. loaded: boolean;
  10. onChangeSlug(prev: Organization, next: Partial<Organization>): void;
  11. onRemoveSuccess(slug: string): void;
  12. onUpdate(org: Partial<Organization>): void;
  13. remove(slug: string): void;
  14. state: Organization[];
  15. }
  16. const storeConfig: OrganizationsStoreDefinition = {
  17. state: [],
  18. loaded: false,
  19. // So we can use Reflux.connect in a component mixin
  20. getInitialState() {
  21. return this.state;
  22. },
  23. init() {
  24. // XXX: Do not use `this.listenTo` in this store. We avoid usage of reflux
  25. // listeners due to their leaky nature in tests.
  26. this.state = [];
  27. this.loaded = false;
  28. },
  29. onUpdate(org) {
  30. let match = false;
  31. this.state.forEach((existing, idx) => {
  32. if (existing.id === org.id) {
  33. this.state[idx] = {...existing, ...org};
  34. match = true;
  35. }
  36. });
  37. if (!match) {
  38. throw new Error(
  39. 'Cannot update an organization that is not in the OrganizationsStore'
  40. );
  41. }
  42. this.trigger(this.state);
  43. },
  44. onChangeSlug(prev, next) {
  45. if (prev.slug === next.slug) {
  46. return;
  47. }
  48. this.remove(prev.slug);
  49. this.addOrReplace({...prev, ...next});
  50. },
  51. onRemoveSuccess(slug) {
  52. this.remove(slug);
  53. },
  54. get(slug) {
  55. return this.state.find((item: Organization) => item.slug === slug);
  56. },
  57. getAll() {
  58. return this.state;
  59. },
  60. getState() {
  61. return this.state;
  62. },
  63. remove(slug) {
  64. this.state = this.state.filter(item => slug !== item.slug);
  65. this.trigger(this.state);
  66. },
  67. addOrReplace(item) {
  68. let match = false;
  69. this.state.forEach((existing, idx) => {
  70. if (existing.id === item.id) {
  71. this.state[idx] = {...existing, ...item};
  72. match = true;
  73. }
  74. });
  75. if (!match) {
  76. this.state = [...this.state, item];
  77. }
  78. this.trigger(this.state);
  79. },
  80. load(items: Organization[]) {
  81. this.state = items;
  82. this.loaded = true;
  83. this.trigger(items);
  84. },
  85. };
  86. const OrganizationsStore = createStore(storeConfig);
  87. export default OrganizationsStore;