web-class-frontend/app/stores/user.ts

75 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-05-03 19:34:43 +08:00
export interface UserInfo {
2025-04-23 17:43:14 +08:00
userId: string;
userName: string;
userEmail: string;
userAvatarPath: string;
2025-05-03 19:34:43 +08:00
userAmount: string;
userBirthday: string;
}
export class ExampleUserInfo implements UserInfo {
userId = '';
userName = '';
userEmail = '';
userAvatarPath = '';
userAmount = '0';
userBirthday = '';
2025-05-03 19:34:43 +08:00
}
export interface UserState extends UserInfo {
lastGetTime: Date;
2025-05-03 19:34:43 +08:00
usernameOrEmail: string;
userAvatarUrl: string;
2025-04-23 17:43:14 +08:00
}
export const useUserStore = defineStore('User', {
state: (): UserState => ({
userId: '',
2025-05-03 19:34:43 +08:00
userName: '',
2025-04-23 17:43:14 +08:00
userEmail: '',
userAvatarPath: '',
2025-05-03 19:34:43 +08:00
userAmount: '',
userBirthday: '',
2025-05-03 19:34:43 +08:00
lastGetTime: new Date(),
usernameOrEmail: '',
userAvatarUrl: '',
2025-04-23 17:43:14 +08:00
}),
2025-05-03 19:34:43 +08:00
actions: {
async getUserInfo() {
const { $http } = useNuxtApp();
try {
const res = await $http.GET<UserInfo>('/user/info');
this.userId = res.data.userId;
this.userName = res.data.userName;
this.userEmail = res.data.userEmail;
this.userAvatarPath = res.data.userAvatarPath;
this.userAmount = res.data.userAmount;
this.userBirthday = res.data.userBirthday;
2025-05-03 19:34:43 +08:00
this.lastGetTime = new Date();
} catch (error) {
console.error('Error fetching user info:', error);
}
},
async getAvatarURL() {
const now = new Date();
console.log('Current time:', now);
if (
this.userAvatarUrl !== '' &&
now.getTime() - this.lastGetTime.getTime() < 1000 * 60 * 9
) {
console.log('Using cached avatar URL');
console.log('Cached avatar URL:', this.userAvatarUrl);
return this.userAvatarUrl;
2025-05-03 19:34:43 +08:00
}
console.log('Fetching new avatar URL');
2025-05-03 19:34:43 +08:00
this.lastGetTime = now;
const { $http } = useNuxtApp();
try {
const res = await $http.GET<string>('/user/avatar');
this.userAvatarUrl = res.data;
console.log('User avatar URL:', this.userAvatarUrl);
return this.userAvatarUrl;
2025-05-03 19:34:43 +08:00
} catch (error) {
console.error('Error fetching user avatar:', error);
}
},
},
2025-04-23 17:43:14 +08:00
});