phanpy/src/utils/store-utils.js

54 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-01-11 08:28:42 +03:00
import store from './store';
export function getAccount(id) {
2023-01-11 08:28:42 +03:00
const accounts = store.local.getJSON('accounts') || [];
return accounts.find((a) => a.info.id === id) || accounts[0];
}
export function getCurrentAccount() {
2023-01-11 08:28:42 +03:00
const currentAccount = store.session.get('currentAccount');
const account = getAccount(currentAccount);
2023-01-11 08:28:42 +03:00
return account;
}
export function getCurrentAccountNS() {
const account = getCurrentAccount();
const {
instanceURL,
info: { id },
} = account;
return `${id}@${instanceURL}`;
}
export function saveAccount(account) {
const accounts = store.local.getJSON('accounts') || [];
const acc = accounts.find((a) => a.info.id === account.info.id);
if (acc) {
acc.info = account.info;
acc.instanceURL = account.instanceURL;
acc.accessToken = account.accessToken;
} else {
accounts.push(account);
}
store.local.setJSON('accounts', accounts);
store.session.set('currentAccount', account.info.id);
}
let currentInstance = null;
export function getCurrentInstance() {
if (currentInstance) return currentInstance;
try {
const account = getCurrentAccount();
const instances = store.local.getJSON('instances');
const instance = account.instanceURL.toLowerCase();
return (currentInstance = instances[instance]);
} catch (e) {
console.error(e);
alert('Failed to load instance configuration. Please try again.');
// Temporary fix for corrupted data
store.local.del('instances');
location.reload();
return {};
}
}