organizationsStore.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. getState(): Organization[];
  10. load(items: Organization[]): void;
  11. loaded: boolean;
  12. onChangeSlug(prev: Organization, next: Organization): void;
  13. onRemoveSuccess(slug: string): void;
  14. onUpdate(org: 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. this.add(org);
  32. },
  33. onChangeSlug(prev, next) {
  34. if (prev.slug === next.slug) {
  35. return;
  36. }
  37. this.remove(prev.slug);
  38. this.add(next);
  39. },
  40. onRemoveSuccess(slug) {
  41. this.remove(slug);
  42. },
  43. get(slug) {
  44. return this.state.find((item: Organization) => item.slug === slug);
  45. },
  46. getAll() {
  47. return this.state;
  48. },
  49. getState() {
  50. return this.state;
  51. },
  52. remove(slug) {
  53. this.state = this.state.filter(item => slug !== item.slug);
  54. this.trigger(this.state);
  55. },
  56. add(item) {
  57. let match = false;
  58. this.state.forEach((existing, idx) => {
  59. if (existing.id === item.id) {
  60. item = {...existing, ...item};
  61. this.state[idx] = item;
  62. match = true;
  63. }
  64. });
  65. if (!match) {
  66. this.state = [...this.state, item];
  67. }
  68. this.trigger(this.state);
  69. },
  70. load(items: Organization[]) {
  71. this.state = items;
  72. this.loaded = true;
  73. this.trigger(items);
  74. },
  75. };
  76. const OrganizationsStore = createStore(makeSafeRefluxStore(storeConfig));
  77. export default OrganizationsStore;