Skip to content

Commit

Permalink
refactor(backend): throw exception instead of returning null
Browse files Browse the repository at this point in the history
  • Loading branch information
davidyuk authored and CedrikNikita committed Aug 20, 2021
1 parent 5a0abb0 commit fbfe678
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 71 deletions.
38 changes: 19 additions & 19 deletions src/components/UserInfo.vue
Original file line number Diff line number Diff line change
Expand Up @@ -353,11 +353,14 @@ export default {
...mapActions('backend', ['setCookies']),
async reloadBalance() {
await this.$watchUntilTruly(() => this.sdk);
this.balance = await this.sdk.balance(this.address).catch(() => 0);
this.balance = await this.sdk.balance(this.address).catch((error) => {
if (error.status !== 404) throw error;
return 0;
});
},
async resetEditedValues() {
this.editMode = false;
await this.getProfile();
await this.reloadProfile();
},
async saveProfile() {
await this.backendAuth('sendProfileData', {
Expand All @@ -377,24 +380,21 @@ export default {
await this.resetEditedValues();
},
async reloadData() {
this.getProfile();
await Backend.getSenderStats(this.address).then((stats) => {
this.userStats = stats;
});
await Promise.all([
this.reloadProfile(),
Backend.getSenderStats(this.address).then((stats) => {
this.userStats = stats;
}),
]);
},
async getProfile() {
await Backend.getProfile(this.address)
.then((profile) => {
if (!profile) {
return;
}
this.profile = profile;
this.profile.location = this.profile.location || '';
this.profile.biography = this.profile.biography || '';
this.profile.coverImage = this.profile.coverImage || '';
this.$store.commit('setUserProfile', profile);
})
.catch(console.error);
async reloadProfile() {
this.profile = {
location: '',
biography: '',
coverImage: '',
...await Backend.getProfile(this.address),
};
if (this.address === this.currentAddress) this.$store.commit('setUserProfile', this.profile);
},
},
};
Expand Down
24 changes: 13 additions & 11 deletions src/components/layout/sendTip/SendTip.vue
Original file line number Diff line number Diff line change
Expand Up @@ -115,31 +115,33 @@ export default {
const amount = shiftDecimalPlaces(this.sendTipForm.amount,
this.inputToken !== null ? this.tokenInfo[this.inputToken].decimals : 18).toFixed();
this.$store.dispatch('aeternity/tip', {
url: this.sendTipForm.url,
title: this.sendTipForm.title,
amount,
tokenAddress: this.inputToken,
}).then(async () => {
try {
await this.$store.dispatch('aeternity/tip', {
url: this.sendTipForm.url,
title: this.sendTipForm.title,
amount,
tokenAddress: this.inputToken,
});
this.clearTipForm();
this.$store.dispatch('modals/open', {
name: 'success',
title: this.$t('components.layout.SendTip.SuccessHeader'),
body: this.$t('components.layout.SendTip.SuccessText'),
});
EventBus.$emit('reloadData');
}).catch((e) => {
this.sendingTip = false;
if (e.code && e.code === 4) {
} catch (error) {
if (error.code && error.code === 4) {
return;
}
console.error(e);
console.error(error);
this.$store.dispatch('modals/open', {
name: 'failure',
title: this.$t('components.layout.SendTip.ErrorHeader'),
body: this.$t('components.layout.SendTip.ErrorText'),
});
});
} finally {
this.sendingTip = false;
}
},
clearTipForm() {
this.sendTipForm = { amount: 0, url: '', title: '' };
Expand Down
18 changes: 7 additions & 11 deletions src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import modals from './plugins/modals';
import backend from './modules/backend';
import aeternity from './modules/aeternity';
import Backend from '../utils/backend';
import { handleUnknownError, fetchJson } from '../utils';
import { fetchJson } from '../utils';

Vue.use(Vuex);

Expand Down Expand Up @@ -51,13 +51,7 @@ export default () => new Vuex.Store({
},
async updateTokensBalanceAndPrice({ state: { address, middleware }, commit, dispatch }) {
const tokens = await Backend.getTokenBalances(address);
let knownTokens;
try {
knownTokens = (await Backend.getWordRegistry()).map((item) => item.tokenAddress);
} catch (error) {
handleUnknownError(error);
return;
}
const knownTokens = (await Backend.getWordRegistry()).map((item) => item.tokenAddress);
if (!middleware) await dispatch('initMiddleware');
await Promise.all(Object.entries(tokens).map(async ([token]) => {
commit('addTokenBalance', {
Expand All @@ -67,8 +61,7 @@ export default () => new Vuex.Store({
if (knownTokens.includes(token)) {
commit('addTokenPrice', {
token,
price: await Backend.getWordSaleDetailsByToken(token)
.then((s) => s.buyPrice).catch(() => null),
price: await Backend.getWordSaleDetailsByToken(token).then((s) => s.buyPrice),
});
}
}));
Expand Down Expand Up @@ -114,7 +107,10 @@ export default () => new Vuex.Store({
dispatch('updatePinnedItems'),
dispatch('updateUserProfile'),
(async () => {
const balance = await sdk.balance(address).catch(() => 0);
const balance = await sdk.balance(address).catch((error) => {
if (error.status !== 404) throw error;
return 0;
});
commit('updateBalance', balance);
})(),
dispatch('updateTokensBalanceAndPrice'),
Expand Down
6 changes: 1 addition & 5 deletions src/store/modules/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,6 @@ export default {
Backend.getTipById(id),
Backend.getTipComments(id),
]);
// TODO: Remove after backend methods start to throw exceptions on not found
if (!tip) throw new Error(`Can't find tip with id: ${id}`);
commit('setTip', {
id,
value: {
Expand All @@ -101,8 +99,6 @@ export default {
},
async reloadComment({ commit }, id) {
const value = await Backend.getCommentById(id);
// TODO: Remove after backend methods start to throw exceptions on not found
if (!value) throw new Error(`Can't find comment with id: ${id}`);
commit('setComment', { id, value });
},
async awaitTip(_, id) {
Expand All @@ -119,7 +115,7 @@ export default {
commit('setStats', { ...stats, height });
},
async reloadPrices({ commit }) {
commit('setPrices', (await Backend.getPrice())?.aeternity);
commit('setPrices', (await Backend.getPrice()).aeternity);
},
// eslint-disable-next-line consistent-return
async callWithAuth({
Expand Down
31 changes: 6 additions & 25 deletions src/utils/backend.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,9 @@
export const wrapTry = async (promise) => {
try {
return promise.then((res) => {
if (!res) {
console.error(new Error('Response is undefined'));
return null;
}
if (!res.ok) throw new Error(`Request failed with ${res.status}`);
return res.json();
}).catch((error) => {
console.error(error);
return null;
});
} catch (error) {
console.error(error);
return null;
}
};
import { fetchJson } from '.';

const backendFetch = (path, ...args) => wrapTry(
fetch(`${process.env.VUE_APP_BACKEND_URL}/${path}`, ...args).catch((err) => console.error(err)),
const backendFetch = (path, ...args) => fetchJson(
`${process.env.VUE_APP_BACKEND_URL}/${path}`, ...args,
);

const backendFetchNoTimeout = (path, ...args) => fetch(`${process.env.VUE_APP_BACKEND_URL}/${path}`, ...args)
.catch((err) => console.error(err));

export default class Backend {
static getTipComments = async (tipId) => backendFetch(`comment/api/tip/${encodeURIComponent(tipId)}`);

Expand Down Expand Up @@ -106,7 +86,7 @@ export default class Backend {
return backendFetch(`tips${query}`);
};

static addToken = async (address) => backendFetchNoTimeout('tokenCache/addToken', {
static addToken = async (address) => backendFetch('tokenCache/addToken', {
method: 'post',
body: JSON.stringify({ address }),
headers: { 'Content-Type': 'application/json' },
Expand All @@ -127,7 +107,8 @@ export default class Backend {
if (ordering) queryParams.set('ordering', ordering);
if (direction) queryParams.set('direction', direction);
if (search) queryParams.set('search', search);
return process.env.VUE_APP_CONTRACT_V2_ADDRESS ? backendFetch(`tokenCache/wordRegistry?${queryParams.toString()}`) : Promise.resolve({});
return process.env.VUE_APP_CONTRACT_V2_ADDRESS
? backendFetch(`tokenCache/wordRegistry?${queryParams.toString()}`) : Promise.resolve([]);
}

static getWordSaleVotesDetails = async (address) => backendFetch(`tokenCache/wordSaleVotesDetails/${address}`);
Expand Down

0 comments on commit fbfe678

Please sign in to comment.