import { useUserStore } from '#lib/stores' import type { AppCookies, UserLoginRequest } from '#lib/types' import { setIsLogged } from '#lib/utils' import { useResetStore, useAuthService } from '#lib/composables' import { useNuxtApp } from 'nuxt/app' /** * Composable to handle authentication API requests, including login and logout. * * @returns {Object} Methods to handle login and logout actions. * @namespace */ export const useAuthApi = () => { // Get authentication service functions and stores. const { requestLogin, requestLogout } = useAuthService() const store = useUserStore() const resetStore = useResetStore() const $appCookies = useNuxtApp().$appCookies as AppCookies /** * Handles user login by making an API request. * * @param requestUser - The login request payload. * @returns {Promise} */ const onLogin = async (requestUser: UserLoginRequest) => { // Make login request using the provided credentials. const { data, error } = await requestLogin(requestUser) // If login is successful, handle the response. if (data.value) { const user = data.value.data $appCookies.token.value = user.token // Save token in cookies. $appCookies.gpToken.value = user.token store.setUser(user) // Update user store with user information. setIsLogged(true) // Mark user as logged in. } // If there's an error, throw it to be handled by the caller. if (error.value) { throw error.value } } /** * Handles user logout by making an API request. * * @returns {Promise} */ const onLogout = async () => { // Make logout request. const { error } = await requestLogout() // If there's an error, throw it to be handled by the caller. if (error.value) { throw error.value } // Perform cleanup operations after logout. resetStore.resetAll() // Reset other stores if necessary. store.resetUser() // Clear user information from the store. $appCookies.token.value = null // Remove token from cookies. $appCookies.gpToken.value = null } // Return methods for handling login and logout. return { onLogin, onLogout, } }