useUser.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. interface TUserData {
  2. user_id: number
  3. group_id?: number
  4. teacher_id?: number
  5. branch_id: number
  6. access_token: string
  7. is_student: boolean
  8. }
  9. function findNewKeys(oldObj: object, newObj: object) {
  10. const newKeys = {}
  11. for (const key in newObj) {
  12. if (!(key in oldObj)) {
  13. newKeys[key] = newObj[key]
  14. }
  15. }
  16. if (Object.keys(newKeys).length > 0) {
  17. return newKeys
  18. }
  19. return null
  20. }
  21. export const useUser = defineStore('useUser', () => {
  22. const log = useLogger('useUser')
  23. const data = ref<TUserData>(JSON.parse(localStorage.getItem('ktc_data')!) || {})
  24. function setAuthData(access_token: string, user_id: number) {
  25. data.value.access_token = access_token
  26. data.value.user_id = user_id
  27. }
  28. function logout() {
  29. localStorage.removeItem('ktc_data')
  30. return navigateTo('/auth', { external: true, replace: true })
  31. }
  32. watch(() => ({ ...data.value }), (upd, prev) => {
  33. localStorage.setItem('ktc_data', JSON.stringify(upd))
  34. log.success('Store was updated:', findNewKeys(prev, upd))
  35. }, {
  36. deep: true,
  37. })
  38. return { data, setAuthData, logout }
  39. })