organizationStore.tsx 2.3 KB

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