organizationsStore.tsx 2.4 KB

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