index.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { defineStore } from 'pinia';
  2. import { fetchUserInfo, fetchUsernameLogin } from '@/api/user';
  3. import { fetchMyWallet } from '@/api/wallet';
  4. import { IAuth, IRole } from '@/interface';
  5. import { IUser } from '@/types/IUser';
  6. import cache from '@/utils/cache';
  7. type UserRootState = {
  8. userInfo?: IUser;
  9. token?: string | null;
  10. roles?: IRole[];
  11. auths?: IAuth[];
  12. };
  13. export const useUserStore = defineStore('user', {
  14. state: (): UserRootState => {
  15. return {
  16. token: cache.getStorageExp('token'),
  17. roles: undefined,
  18. userInfo: undefined,
  19. auths: undefined,
  20. };
  21. },
  22. actions: {
  23. setUserInfo(res: UserRootState['userInfo']) {
  24. this.userInfo = res;
  25. },
  26. setToken(res: UserRootState['token'], exp: number) {
  27. cache.setStorageExp('token', res, exp);
  28. this.token = res;
  29. },
  30. setRoles(res: UserRootState['roles']) {
  31. this.roles = res;
  32. },
  33. setAuths(res: UserRootState['auths']) {
  34. this.auths = res;
  35. },
  36. logout() {
  37. cache.clearStorage('token');
  38. this.token = undefined;
  39. this.userInfo = undefined;
  40. this.roles = undefined;
  41. },
  42. async usernameLogin({ username, password }) {
  43. try {
  44. const { data: token } = await fetchUsernameLogin({
  45. username,
  46. password,
  47. });
  48. this.setToken(token, 24);
  49. return token;
  50. } catch (error: any) {
  51. // 错误返回401,全局的响应拦截会打印报错信息
  52. return null;
  53. }
  54. },
  55. async updateMyWallet() {
  56. const res = await fetchMyWallet();
  57. if (res.code === 200) {
  58. if (this.userInfo?.wallet?.balance) {
  59. this.userInfo.wallet.balance = res.data.balance;
  60. }
  61. }
  62. },
  63. async getUserInfo() {
  64. try {
  65. const { code, data } = await fetchUserInfo();
  66. this.setUserInfo(data);
  67. this.setRoles(data.roles);
  68. this.setAuths(data.auths);
  69. return { code, data };
  70. } catch (error) {
  71. return error;
  72. }
  73. },
  74. },
  75. });