code refactor

This commit is contained in:
MaysWind
2021-01-05 22:55:34 +08:00
parent fbfba764d4
commit abae1c85e7
16 changed files with 172 additions and 122 deletions
+115
View File
@@ -0,0 +1,115 @@
import services from '../lib/services.js';
import logger from '../lib/logger.js';
import utils from '../lib/utils.js';
import {
STORE_LATEST_EXCHANGE_RATES
} from './mutations.js';
const exchangeRatesLocalStorageKey = 'lab_app_exchange_rates';
function getLatestExchangeRates(context, { silent, force }) {
const currentExchangeRateData = context.state.latestExchangeRates;
const now = new Date();
if (!force) {
if (currentExchangeRateData && currentExchangeRateData.time && currentExchangeRateData.data &&
currentExchangeRateData.data.date === utils.formatDate(now, 'YYYY-MM-DD')) {
return currentExchangeRateData.data;
}
if (currentExchangeRateData && currentExchangeRateData.time && currentExchangeRateData.data &&
utils.formatUnixTime(currentExchangeRateData.time, 'YYYY-MM-DD HH') === utils.formatDate(now, 'YYYY-MM-DD HH')) {
return currentExchangeRateData.data;
}
}
return new Promise((resolve, reject) => {
services.getLatestExchangeRates({
ignoreError: silent
}).then(response => {
const data = response.data;
if (!data || !data.success || !data.result) {
reject({ message: 'Unable to get exchange rates data' });
return;
}
context.commit(STORE_LATEST_EXCHANGE_RATES, {
time: utils.getUnixTime(now),
data: data.result
});
resolve(data.result);
}).catch(error => {
logger.error('failed to get latest exchange rates data', error);
if (error && error.processed) {
reject(error);
} else if (error.response && error.response.data && error.response.data.errorMessage) {
reject({ error: error.response.data });
} else {
reject({ message: 'Unable to get exchange rates data' });
}
});
});
}
function exchangeRatesLastUpdateDate(state) {
const exchangeRates = state.latestExchangeRates || {};
return exchangeRates && exchangeRates.data ? exchangeRates.data.date : null;
}
function getExchangedAmount(state) {
return (amount, fromCurrency, toCurrency) => {
if (!state.latestExchangeRates || !state.latestExchangeRates.data || !state.latestExchangeRates.data.exchangeRates) {
return null;
}
const exchangeRates = state.latestExchangeRates.data.exchangeRates;
const exchangeRateMap = {};
for (let i = 0; i < exchangeRates.length; i++) {
const exchangeRate = exchangeRates[i];
exchangeRateMap[exchangeRate.currency] = exchangeRate;
}
const fromCurrencyExchangeRate = exchangeRateMap[fromCurrency];
const toCurrencyExchangeRate = exchangeRateMap[toCurrency];
if (!fromCurrencyExchangeRate || !toCurrencyExchangeRate) {
return null;
}
const exchangeRate = parseFloat(toCurrencyExchangeRate.rate) / parseFloat(fromCurrencyExchangeRate.rate);
if (!utils.isNumber(exchangeRate)) {
return null;
}
return amount * exchangeRate;
};
}
function getExchangeRatesFromLocalStorage() {
const storageData = localStorage.getItem(exchangeRatesLocalStorageKey) || '{}';
return JSON.parse(storageData);
}
function setExchangeRatesToLocalStorage(value) {
const storageData = JSON.stringify(value);
localStorage.setItem(exchangeRatesLocalStorageKey, storageData);
}
function clearExchangeRatesFromLocalStorage() {
localStorage.removeItem(exchangeRatesLocalStorageKey);
}
export default {
getLatestExchangeRates,
exchangeRatesLastUpdateDate,
getExchangedAmount,
getExchangeRatesFromLocalStorage,
setExchangeRatesToLocalStorage,
clearExchangeRatesFromLocalStorage,
}
+15
View File
@@ -7,6 +7,8 @@ import {
STORE_USER_INFO,
CLEAR_USER_INFO,
STORE_LATEST_EXCHANGE_RATES,
LOAD_ACCOUNT_LIST,
ADD_ACCOUNT_TO_ACCOUNT_LIST,
SAVE_ACCOUNT_IN_ACCOUNT_LIST,
@@ -28,6 +30,7 @@ import {
import user from './user.js';
import token from './token.js';
import exchangeRates from './exchangeRates.js';
import account from './account.js';
import transactionTag from './transactionTag.js';
@@ -35,6 +38,7 @@ const stores = {
strict: process.env.NODE_ENV !== 'production',
state: {
currentUserInfo: userState.getUserInfo(),
latestExchangeRates: exchangeRates.getExchangeRatesFromLocalStorage(),
allAccounts: [],
allAccountsMap: {},
allCategorizedAccounts: {},
@@ -49,11 +53,14 @@ const stores = {
getters: {
currentUserNickname: user.currentUserNickname,
currentUserDefaultCurrency: user.currentUserDefaultCurrency,
exchangeRatesLastUpdateDate: exchangeRates.exchangeRatesLastUpdateDate,
getExchangedAmount: exchangeRates.getExchangedAmount,
allAvailableAccountsCount: account.allAvailableAccountsCount,
allVisibleAccountsCount: account.allVisibleAccountsCount,
},
mutations: {
[RESET_STATE] (state) {
state.latestExchangeRates = {};
state.allAccounts = [];
state.allAccountsMap = {};
state.allCategorizedAccounts = {};
@@ -64,6 +71,8 @@ const stores = {
state.allTransactionTagsMap = {};
state.transactionTagListStateInvalid = true;
state.transactions = [];
exchangeRates.clearExchangeRatesFromLocalStorage();
},
[STORE_USER_INFO] (state, userInfo) {
state.currentUserInfo = userInfo;
@@ -73,6 +82,10 @@ const stores = {
state.currentUserInfo = null;
userState.clearUserInfo();
},
[STORE_LATEST_EXCHANGE_RATES] (state, latestExchangeRates) {
state.latestExchangeRates = latestExchangeRates;
exchangeRates.setExchangeRatesToLocalStorage(latestExchangeRates);
},
[LOAD_ACCOUNT_LIST] (state, accounts) {
state.allAccounts = accounts;
state.allAccountsMap = {};
@@ -250,10 +263,12 @@ const stores = {
getCurrentUserProfile: user.getCurrentUserProfile,
updateUserProfile: user.updateUserProfile,
clearUserInfoState: user.clearUserInfoState,
resetState: user.resetState,
getAllTokens: token.getAllTokens,
refreshTokenAndRevokeOldToken: token.refreshTokenAndRevokeOldToken,
revokeToken: token.revokeToken,
revokeAllTokens: token.revokeAllTokens,
getLatestExchangeRates: exchangeRates.getLatestExchangeRates,
loadAllAccounts: account.loadAllAccounts,
saveAccount: account.saveAccount,
getAccount: account.getAccount,
+2
View File
@@ -3,6 +3,8 @@ export const RESET_STATE = 'RESET_STATE';
export const STORE_USER_INFO = 'STORE_USER_INFO';
export const CLEAR_USER_INFO = 'CLEAR_USER_INFO';
export const STORE_LATEST_EXCHANGE_RATES = 'STORE_LATEST_EXCHANGE_RATES';
export const LOAD_ACCOUNT_LIST = 'LOAD_ACCOUNT_LIST';
export const ADD_ACCOUNT_TO_ACCOUNT_LIST = 'ADD_ACCOUNT_TO_ACCOUNT_LIST';
export const SAVE_ACCOUNT_IN_ACCOUNT_LIST = 'SAVE_ACCOUNT_IN_ACCOUNT_LIST';
+5
View File
@@ -264,6 +264,10 @@ function clearUserInfoState(context) {
context.commit(CLEAR_USER_INFO);
}
function resetState(context) {
context.commit(RESET_STATE);
}
function currentUserNickname(state) {
const userInfo = state.currentUserInfo || {};
return userInfo.nickname || userInfo.username || null;
@@ -282,6 +286,7 @@ export default {
getCurrentUserProfile,
updateUserProfile,
clearUserInfoState,
resetState,
currentUserNickname,
currentUserDefaultCurrency
}