elearning/frontend_management/services/user.service.ts

122 lines
3.2 KiB
TypeScript
Raw Normal View History

// API Response structure from /api/user/me
export interface UserProfileResponse {
id: number;
username: string;
email: string;
email_verified_at: string | null;
updated_at: string;
created_at: string;
role: {
code: string;
name: {
en: string;
th: string;
};
};
profile: {
prefix: {
en: string;
th: string;
};
first_name: string;
last_name: string;
avatar_url: string | null;
birth_date: string | null;
phone: string | null;
};
}
2026-02-02 09:31:22 +07:00
export interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
// Request body for PUT /api/user/me
export interface UpdateProfileRequest {
prefix?: {
en: string;
th: string;
};
first_name: string;
last_name: string;
phone?: string | null;
avatar_url?: string | null;
birth_date?: string | null;
}
// Helper function to get auth token from cookie
const getAuthToken = (): string => {
const tokenCookie = useCookie('token');
return tokenCookie.value || '';
};
export const userService = {
async getProfile(): Promise<UserProfileResponse> {
const config = useRuntimeConfig();
const token = getAuthToken();
const response = await $fetch<UserProfileResponse>('/api/user/me', {
baseURL: config.public.apiBaseUrl as string,
headers: {
Authorization: `Bearer ${token}`
}
});
return response;
},
2026-02-02 09:31:22 +07:00
async updateProfile(data: UpdateProfileRequest): Promise<ApiResponse<UserProfileResponse>> {
const config = useRuntimeConfig();
const token = getAuthToken();
2026-02-02 09:31:22 +07:00
const response = await $fetch<ApiResponse<UserProfileResponse>>('/api/user/me', {
method: 'PUT',
baseURL: config.public.apiBaseUrl as string,
headers: {
Authorization: `Bearer ${token}`
},
body: data
});
return response;
},
2026-02-02 09:31:22 +07:00
async changePassword(oldPassword: string, newPassword: string): Promise<ApiResponse<null>> {
const config = useRuntimeConfig();
const token = getAuthToken();
2026-02-02 09:31:22 +07:00
const response = await $fetch<ApiResponse<null>>('/api/user/change-password', {
method: 'POST',
baseURL: config.public.apiBaseUrl as string,
headers: {
Authorization: `Bearer ${token}`
},
body: {
oldPassword,
newPassword
}
});
2026-02-02 09:31:22 +07:00
return response;
},
2026-02-02 09:31:22 +07:00
async uploadAvatar(file: File): Promise<ApiResponse<{ avatar_url: string; id: number }>> {
const config = useRuntimeConfig();
const token = getAuthToken();
const formData = new FormData();
formData.append('file', file);
2026-02-02 09:31:22 +07:00
const response = await $fetch<ApiResponse<{ avatar_url: string; id: number }>>('/api/user/upload-avatar', {
method: 'POST',
baseURL: config.public.apiBaseUrl as string,
headers: {
Authorization: `Bearer ${token}`
},
body: formData
});
2026-02-02 09:31:22 +07:00
return response;
}
};