organizationsStore.tsx 2.0 KB

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