settings.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { action, Action, thunk, Thunk } from "easy-peasy";
  2. import axios from "axios";
  3. import { getAxiosConfig } from "../utils";
  4. import { StoreModel } from "./store";
  5. import { APIv2 } from "../consts";
  6. export interface Domain {
  7. id: string;
  8. address: string;
  9. banned: boolean;
  10. created_at: string;
  11. homepage?: string;
  12. updated_at: string;
  13. }
  14. export interface NewDomain {
  15. address: string;
  16. homepage?: string;
  17. }
  18. export interface SettingsResp {
  19. apikey: string;
  20. email: string;
  21. domains: Domain[];
  22. }
  23. export interface Settings {
  24. domains: Array<Domain>;
  25. apikey: string;
  26. email: string;
  27. fetched: boolean;
  28. setSettings: Action<Settings, SettingsResp>;
  29. getSettings: Thunk<Settings, null, null, StoreModel>;
  30. setApiKey: Action<Settings, string>;
  31. generateApiKey: Thunk<Settings>;
  32. addDomain: Action<Settings, Domain>;
  33. removeDomain: Action<Settings, string>;
  34. saveDomain: Thunk<Settings, NewDomain>;
  35. deleteDomain: Thunk<Settings, string>;
  36. }
  37. export const settings: Settings = {
  38. domains: [],
  39. email: null,
  40. apikey: null,
  41. fetched: false,
  42. getSettings: thunk(async (actions, payload, { getStoreActions }) => {
  43. getStoreActions().loading.show();
  44. const res = await axios.get(APIv2.Users, getAxiosConfig());
  45. actions.setSettings(res.data);
  46. getStoreActions().loading.hide();
  47. }),
  48. generateApiKey: thunk(async actions => {
  49. const res = await axios.post(
  50. APIv2.AuthGenerateApikey,
  51. null,
  52. getAxiosConfig()
  53. );
  54. actions.setApiKey(res.data.apikey);
  55. }),
  56. deleteDomain: thunk(async (actions, id) => {
  57. await axios.delete(`${APIv2.Domains}/${id}`, getAxiosConfig());
  58. actions.removeDomain(id);
  59. }),
  60. setSettings: action((state, payload) => {
  61. state.apikey = payload.apikey;
  62. state.domains = payload.domains;
  63. state.email = payload.email;
  64. state.fetched = true;
  65. }),
  66. setApiKey: action((state, payload) => {
  67. state.apikey = payload;
  68. }),
  69. addDomain: action((state, payload) => {
  70. state.domains.push(payload);
  71. }),
  72. removeDomain: action((state, id) => {
  73. state.domains = state.domains.filter(d => d.id !== id);
  74. }),
  75. saveDomain: thunk(async (actions, payload) => {
  76. const res = await axios.post(APIv2.Domains, payload, getAxiosConfig());
  77. actions.addDomain(res.data);
  78. })
  79. };