|
1 |
| -import { defineStore } from 'pinia'; |
| 1 | +import { defineStore, storeToRefs } from 'pinia'; |
2 | 2 | import { ref } from 'vue';
|
3 | 3 |
|
4 | 4 | import type { TraktClientAuthentication } from '~/models/trakt/trakt-authentication.model';
|
5 | 5 |
|
| 6 | +import { storage } from '~/utils/browser/browser-storage.utils'; |
| 7 | + |
6 | 8 | export const useSettingsStore = defineStore('settings', () => {
|
7 | 9 | const auth = ref<TraktClientAuthentication>();
|
8 |
| - const setAuth = (_auth?: TraktClientAuthentication) => { |
9 |
| - auth.value = _auth; |
10 |
| - }; |
11 |
| - |
12 | 10 | const isAuthenticated = ref(false);
|
| 11 | + |
13 | 12 | const setAuthenticated = (authenticated: boolean = false) => {
|
14 | 13 | isAuthenticated.value = authenticated;
|
15 | 14 | };
|
16 | 15 |
|
17 |
| - return { auth, setAuth, isAuthenticated, setAuthenticated }; |
| 16 | + const syncSetAuth = (_auth: TraktClientAuthentication) => storage.sync.set('settings.auth', _auth); |
| 17 | + const syncClearAuth = () => storage.sync.remove('settings.auth'); |
| 18 | + const syncRestoreAuth = () => |
| 19 | + storage.sync.get<TraktClientAuthentication>('settings.auth').then(_auth => { |
| 20 | + auth.value = _auth; |
| 21 | + setAuthenticated(!!_auth?.access_token); |
| 22 | + return _auth; |
| 23 | + }); |
| 24 | + |
| 25 | + const setAuth = (_auth?: TraktClientAuthentication) => { |
| 26 | + auth.value = _auth; |
| 27 | + setAuthenticated(!!_auth?.access_token); |
| 28 | + console.info('settings-store', 'Auth changed', _auth); |
| 29 | + if (_auth?.access_token) { |
| 30 | + syncSetAuth(_auth).then(() => console.info('settings-store', 'Auth saved', _auth)); |
| 31 | + } else { |
| 32 | + syncClearAuth().then(() => console.info('settings-store', 'Auth cleared')); |
| 33 | + } |
| 34 | + }; |
| 35 | + |
| 36 | + return { auth, setAuth, isAuthenticated, setAuthenticated, syncRestoreAuth }; |
18 | 37 | });
|
| 38 | + |
| 39 | +export const useSettingsStoreRefs = () => storeToRefs(useSettingsStore()); |
0 commit comments