ViewStore.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { types } from 'mobx-state-tree';
  2. import { toJS } from 'mobx';
  3. import { toUrlParams } from 'app/core/utils/url';
  4. const QueryInnerValueType = types.union(types.string, types.boolean, types.number);
  5. const QueryValueType = types.union(QueryInnerValueType, types.array(QueryInnerValueType));
  6. export const ViewStore = types
  7. .model({
  8. path: types.string,
  9. query: types.map(QueryValueType),
  10. routeParams: types.map(QueryValueType),
  11. })
  12. .views(self => ({
  13. get currentUrl() {
  14. let path = self.path;
  15. if (self.query.size) {
  16. path += '?' + toUrlParams(toJS(self.query));
  17. }
  18. return path;
  19. },
  20. }))
  21. .actions(self => {
  22. function updateQuery(query: any) {
  23. self.query.clear();
  24. for (let key of Object.keys(query)) {
  25. self.query.set(key, query[key]);
  26. }
  27. }
  28. function updateRouteParams(routeParams: any) {
  29. self.routeParams.clear();
  30. for (let key of Object.keys(routeParams)) {
  31. self.routeParams.set(key, routeParams[key]);
  32. }
  33. }
  34. function updatePathAndQuery(path: string, query: any, routeParams: any) {
  35. self.path = path;
  36. updateQuery(query);
  37. updateRouteParams(routeParams);
  38. }
  39. return {
  40. updateQuery,
  41. updatePathAndQuery,
  42. };
  43. });