organizationsStore.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. this.state = [];
  25. this.loaded = false;
  26. },
  27. onUpdate(org) {
  28. let match = false;
  29. this.state.forEach((existing, idx) => {
  30. if (existing.id === org.id) {
  31. this.state[idx] = {...existing, ...org};
  32. match = true;
  33. }
  34. });
  35. if (!match) {
  36. throw new Error(
  37. 'Cannot update an organization that is not in the OrganizationsStore'
  38. );
  39. }
  40. this.trigger(this.state);
  41. },
  42. onChangeSlug(prev, next) {
  43. if (prev.slug === next.slug) {
  44. return;
  45. }
  46. this.remove(prev.slug);
  47. this.addOrReplace({...prev, ...next});
  48. },
  49. onRemoveSuccess(slug) {
  50. this.remove(slug);
  51. },
  52. get(slug) {
  53. return this.state.find((item: Organization) => item.slug === slug);
  54. },
  55. getAll() {
  56. return this.state;
  57. },
  58. getState() {
  59. return this.state;
  60. },
  61. remove(slug) {
  62. this.state = this.state.filter(item => slug !== item.slug);
  63. this.trigger(this.state);
  64. },
  65. addOrReplace(item) {
  66. let match = false;
  67. this.state.forEach((existing, idx) => {
  68. if (existing.id === item.id) {
  69. this.state[idx] = {...existing, ...item};
  70. match = true;
  71. }
  72. });
  73. if (!match) {
  74. this.state = [...this.state, item];
  75. }
  76. this.trigger(this.state);
  77. },
  78. load(items: Organization[]) {
  79. this.state = items;
  80. this.loaded = true;
  81. this.trigger(items);
  82. },
  83. };
  84. const OrganizationsStore = createStore(storeConfig);
  85. export default OrganizationsStore;