Created
September 22, 2025 11:03
-
-
Save maximvl/5f099be460cd3b16c02eb630c8ff95d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { goto } from '$app/navigation' | |
| import { EventlabBaseUrl, queryClient } from '$lib/client' | |
| import type { UserItem } from '$lib/heyapi' | |
| import { | |
| fetchCurrentUserApiUsersCurrentGetQueryKey, | |
| getUsersApiUsersGetOptions, | |
| getUsersApiUsersGetQueryKey, | |
| loginApiLoginPostMutation | |
| } from '$lib/heyapi/@tanstack/svelte-query.gen' | |
| import { createMutation, createQuery } from '@tanstack/svelte-query' | |
| import { get } from 'svelte/store' | |
| class UsersStore { | |
| private _my_user = $state<UserItem | null>(null) | |
| private _login_mutation = createMutation({ | |
| ...loginApiLoginPostMutation({ baseUrl: EventlabBaseUrl }) | |
| }) | |
| private _current_user_query = createQuery({ | |
| ...fetchCurrentUserApiUsersCurrentGetOptions({ | |
| baseUrl: EventlabBaseUrl, | |
| auth: () => localStorage.getItem('auth_token') ?? undefined | |
| }), | |
| retry: false | |
| }) | |
| constructor() { | |
| this._current_user_query.subscribe((query) => { | |
| console.log('current user data', query) | |
| if (query.data) { | |
| this._my_user = query.data | |
| } else { | |
| this._my_user = null | |
| } | |
| console.log('this._my_user', this._my_user) | |
| }) | |
| } | |
| refetchMyUser() { | |
| return queryClient.refetchQueries({ | |
| queryKey: fetchCurrentUserApiUsersCurrentGetQueryKey() | |
| }) | |
| } | |
| login(name: string, pass: string) { | |
| get(this._login_mutation) | |
| .mutateAsync({ body: { username: name, password: pass } }) | |
| .then((response) => { | |
| if (response.token) { | |
| localStorage.setItem('auth_token', response.token) | |
| } | |
| this.refetchMyUser().then(() => { | |
| goto('/') | |
| }) | |
| }) | |
| } | |
| logout() { | |
| localStorage.removeItem('auth_token') | |
| this._my_user = null | |
| } | |
| setMyUser(user: UserItem | null) { | |
| this._my_user = user | |
| } | |
| get myUser() { | |
| return this._my_user | |
| } | |
| } | |
| export default UsersStore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment