organizationsStore.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. add(item: Organization): void;
  7. get(slug: string): Organization | undefined;
  8. getAll(): Organization[];
  9. load(items: Organization[]): void;
  10. loaded: boolean;
  11. onChangeSlug(prev: Organization, next: Organization): void;
  12. onRemoveSuccess(slug: string): void;
  13. onUpdate(org: Organization): void;
  14. remove(slug: string): void;
  15. state: Organization[];
  16. }
  17. const storeConfig: OrganizationsStoreDefinition = {
  18. listenables: [OrganizationsActions],
  19. state: [],
  20. loaded: false,
  21. // So we can use Reflux.connect in a component mixin
  22. getInitialState() {
  23. return this.state;
  24. },
  25. init() {
  26. this.state = [];
  27. this.loaded = false;
  28. },
  29. onUpdate(org: Organization) {
  30. this.add(org);
  31. },
  32. onChangeSlug(prev: Organization, next: Organization) {
  33. if (prev.slug === next.slug) {
  34. return;
  35. }
  36. this.remove(prev.slug);
  37. this.add(next);
  38. },
  39. onRemoveSuccess(slug: string) {
  40. this.remove(slug);
  41. },
  42. get(slug: Organization['slug']) {
  43. return this.state.find((item: Organization) => item.slug === slug);
  44. },
  45. getAll() {
  46. return this.state;
  47. },
  48. remove(slug: Organization['slug']) {
  49. this.state = this.state.filter(item => slug !== item.slug);
  50. this.trigger(this.state);
  51. },
  52. add(item: Organization) {
  53. let match = false;
  54. this.state.forEach((existing, idx) => {
  55. if (existing.id === item.id) {
  56. item = {...existing, ...item};
  57. this.state[idx] = item;
  58. match = true;
  59. }
  60. });
  61. if (!match) {
  62. this.state = [...this.state, item];
  63. }
  64. this.trigger(this.state);
  65. },
  66. load(items: Organization[]) {
  67. this.state = items;
  68. this.loaded = true;
  69. this.trigger(items);
  70. },
  71. };
  72. const OrganizationsStore = createStore(makeSafeRefluxStore(storeConfig));
  73. export default OrganizationsStore;