55 lines
1.2 KiB
TypeScript
55 lines
1.2 KiB
TypeScript
import { useNotification } from '@composables/notification';
|
|
import { UPLOAD_AVATAR } from '@graphql/mutations/user';
|
|
import type { IAvatarUploadResponse } from '@types';
|
|
|
|
export function useAvatarUpload() {
|
|
const { t } = useI18n();
|
|
const userStore = useUserStore();
|
|
const { mutate, onDone, error } = useMutation<IAvatarUploadResponse>(UPLOAD_AVATAR);
|
|
|
|
async function uploadAvatar(event: Event) {
|
|
const file = (event.target as HTMLInputElement).files?.[0];
|
|
if (!file) return;
|
|
|
|
await mutate(
|
|
{
|
|
file,
|
|
},
|
|
{
|
|
context: {
|
|
hasUpload: true,
|
|
},
|
|
});
|
|
}
|
|
|
|
onDone(({ data }) => {
|
|
const user = data?.uploadAvatar.user;
|
|
if (user) {
|
|
userStore.setUser(user);
|
|
useNotification({
|
|
message: t('popup.success.avatarUpload'),
|
|
type: 'success',
|
|
});
|
|
}
|
|
});
|
|
|
|
watch(error, (err) => {
|
|
if (!err) return;
|
|
console.error('useAvatarUpload error:', err);
|
|
let message = t('popup.errors.defaultError');
|
|
if (isGraphQLError(err)) {
|
|
message = err.graphQLErrors?.[0]?.message || message;
|
|
} else {
|
|
message = err.message;
|
|
}
|
|
useNotification({
|
|
message,
|
|
type: 'error',
|
|
title: t('popup.errors.main'),
|
|
});
|
|
});
|
|
|
|
return {
|
|
uploadAvatar,
|
|
};
|
|
}
|