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

54 lines
1.4 KiB
TypeScript

export interface UserInfo {
userId: string;
userName: string;
userEmail: string;
userAvatar: string;
userAmount: string;
lastGetTime: Date;
}
export interface UserState extends UserInfo {
usernameOrEmail: string;
}
export const useUserStore = defineStore('User', {
state: (): UserState => ({
usernameOrEmail: '',
userId: '',
userName: '',
userEmail: '',
userAvatar: '',
userAmount: '',
lastGetTime: new Date(),
}),
actions: {
async getUserInfo() {
const { $http } = useNuxtApp();
try {
const res = await $http.GET<UserInfo>('/user/info');
console.log(res.data);
this.userId = res.data.userId;
this.userName = res.data.userName;
this.userEmail = res.data.userEmail;
this.userAvatar = res.data.userAvatar;
this.userAmount = '500';
this.lastGetTime = new Date();
} catch (error) {
console.error('Error fetching user info:', error);
}
},
async getAvatarURL() {
const now = new Date();
if (now.getTime() - this.lastGetTime.getTime() < 1000 * 60 * 9) {
return this.userAvatar;
}
this.lastGetTime = now;
const { $http } = useNuxtApp();
try {
const res = await $http.GET<string>('/user/avatar');
this.userAvatar = res.data;
} catch (error) {
console.error('Error fetching user avatar:', error);
}
},
},
});