organizationStore.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import {createStore} from 'reflux';
  2. import OrganizationActions from 'sentry/actions/organizationActions';
  3. import {ORGANIZATION_FETCH_ERROR_TYPES} from 'sentry/constants';
  4. import {Organization} from 'sentry/types';
  5. import {makeSafeRefluxStore} from 'sentry/utils/makeSafeRefluxStore';
  6. import RequestError from 'sentry/utils/requestError/requestError';
  7. import {CommonStoreDefinition} from './types';
  8. type UpdateOptions = {
  9. replace?: boolean;
  10. };
  11. type State = {
  12. dirty: boolean;
  13. loading: boolean;
  14. organization: Organization | null;
  15. error?: RequestError | null;
  16. errorType?: string | null;
  17. };
  18. interface OrganizationStoreDefinition extends CommonStoreDefinition<State> {
  19. get(): State;
  20. init(): void;
  21. onFetchOrgError(err: RequestError): void;
  22. onUpdate(org: Organization, options: UpdateOptions): void;
  23. reset(): void;
  24. }
  25. const storeConfig: OrganizationStoreDefinition = {
  26. unsubscribeListeners: [],
  27. init() {
  28. this.reset();
  29. this.unsubscribeListeners.push(
  30. this.listenTo(OrganizationActions.update, this.onUpdate)
  31. );
  32. this.unsubscribeListeners.push(this.listenTo(OrganizationActions.reset, this.reset));
  33. this.unsubscribeListeners.push(
  34. this.listenTo(OrganizationActions.fetchOrgError, this.onFetchOrgError)
  35. );
  36. },
  37. reset() {
  38. this.loading = true;
  39. this.error = null;
  40. this.errorType = null;
  41. this.organization = null;
  42. this.dirty = false;
  43. this.trigger(this.get());
  44. },
  45. onUpdate(updatedOrg: Organization, {replace = false}: UpdateOptions = {}) {
  46. this.loading = false;
  47. this.error = null;
  48. this.errorType = null;
  49. this.organization = replace ? updatedOrg : {...this.organization, ...updatedOrg};
  50. this.dirty = false;
  51. this.trigger(this.get());
  52. },
  53. onFetchOrgError(err: RequestError) {
  54. this.organization = null;
  55. this.errorType = null;
  56. switch (err?.status) {
  57. case 401:
  58. this.errorType = ORGANIZATION_FETCH_ERROR_TYPES.ORG_NO_ACCESS;
  59. break;
  60. case 404:
  61. this.errorType = ORGANIZATION_FETCH_ERROR_TYPES.ORG_NOT_FOUND;
  62. break;
  63. default:
  64. }
  65. this.loading = false;
  66. this.error = err;
  67. this.dirty = false;
  68. this.trigger(this.get());
  69. },
  70. get() {
  71. return {
  72. organization: this.organization,
  73. error: this.error,
  74. loading: this.loading,
  75. errorType: this.errorType,
  76. dirty: this.dirty,
  77. };
  78. },
  79. getState() {
  80. return this.get();
  81. },
  82. };
  83. const OrganizationStore = createStore(makeSafeRefluxStore(storeConfig));
  84. export default OrganizationStore;