import { ref } from 'vue' import { defineStore } from 'pinia' import MyUserModel from "@/models/myUserModel.js"; export const useUserStore = defineStore('user', () => { const user = ref({}); const hasChanged = ref(false); function getCurrentUser() { return this.user.value; } async function setCurrentUser(client) { try { const myUser = await client.get("/api/GetMyUser"); this.user.value = MyUserModel.createFromApiResult(myUser.data); this.hasChanged = false; } catch (e){ this.user.value = MyUserModel.getDefaultUser(); console.log("User not logged.") } } async function updateCurrentUser(client, myUserModel, profilePicture, bannerPicture, websiteIcon) { await client.patch("/api/UpdateMyUser/profile", myUserModel) if (typeof myUserModel.storedDataUrls.profilePictureUrl !== "object") { const haveNewProfilePicture = profilePicture !== null && profilePicture.size !== 0; const updateProfilePictureEndpoint = haveNewProfilePicture ? `/api/UpdateMyUser/profile-picture` : `/api/UpdateMyUser/profile-picture?url=${myUserModel.storedDataUrls.profilePictureUrl}`; const response = await client.post(updateProfilePictureEndpoint, profilePicture, { headers: { 'Content-Type': 'application/octet-stream', } }); if (haveNewProfilePicture) { this.user.value.storedDataUrls.profilePictureUrl = response.data; } } if (typeof myUserModel.storedDataUrls.bannerPictureUrl !== "object") { const haveNewBannerPicture = bannerPicture !== null && bannerPicture.size !== 0; const updateBannerPictureEndpoint = haveNewBannerPicture ? `/api/UpdateMyUser/banner-picture` : `/api/UpdateMyUser/banner-picture?url=${myUserModel.storedDataUrls.bannerPictureUrl}`; const response = await client.post(updateBannerPictureEndpoint, bannerPicture, { headers: { 'Content-Type': 'application/octet-stream', } }); if (haveNewBannerPicture) { this.user.value.storedDataUrls.bannerPictureUrl = response.data; } } if (typeof myUserModel.storedDataUrls.websiteIconUrl !== "object") { const haveNewWebsiteIcon = websiteIcon !== null && websiteIcon.size !== 0; const updateWebsiteIconEndpoint = haveNewWebsiteIcon ? `/api/UpdateMyUser/website-icon` : `/api/UpdateMyUser/website-icon?url=${myUserModel.storedDataUrls.websiteIconUrl}`; const response = await client.post(updateWebsiteIconEndpoint, websiteIcon, { headers: { 'Content-Type': 'application/octet-stream', } }); if (haveNewWebsiteIcon) { this.user.value.storedDataUrls.websiteIconUrl = response.data; } } this.user.value = myUserModel; this.hasChanged = true; } return { user, getCurrentUser, setCurrentUser, updateCurrentUser } })