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

75 lines
2.1 KiB
TypeScript

export interface UserInfo {
userId: string;
userName: string;
userEmail: string;
userAvatarPath: string;
userAmount: string;
userBirthday: string;
}
export class ExampleUserInfo implements UserInfo {
userId = '';
userName = '';
userEmail = '';
userAvatarPath = '';
userAmount = '0';
userBirthday = '';
}
export interface UserState extends UserInfo {
lastGetTime: Date;
usernameOrEmail: string;
userAvatarUrl: string;
}
export const useUserStore = defineStore('User', {
state: (): UserState => ({
userId: '',
userName: '',
userEmail: '',
userAvatarPath: '',
userAmount: '',
userBirthday: '',
lastGetTime: new Date(),
usernameOrEmail: '',
userAvatarUrl: '',
}),
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;
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;
}
console.log('Fetching new avatar URL');
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;
} catch (error) {
console.error('Error fetching user avatar:', error);
}
},
},
});