From 1a442e6b12166de77db999b0ef0054bda22622c7 Mon Sep 17 00:00:00 2001 From: Denis Davidyuk Date: Wed, 7 Jul 2021 10:02:05 +0300 Subject: [PATCH] refactor(backend): throw exception instead of returning `null` --- src/components/UserInfo.vue | 34 +++++++++++------------- src/components/tipRecords/Author.vue | 3 +-- src/components/tipRecords/TipPreview.vue | 3 ++- src/store/index.js | 16 +++++------ src/store/modules/backend.js | 6 +---- src/utils/backend.js | 31 +++++---------------- 6 files changed, 31 insertions(+), 62 deletions(-) diff --git a/src/components/UserInfo.vue b/src/components/UserInfo.vue index fdf605da4..d16167265 100644 --- a/src/components/UserInfo.vue +++ b/src/components/UserInfo.vue @@ -344,7 +344,7 @@ export default { }, async resetEditedValues() { this.editMode = false; - await this.getProfile(); + await this.reloadProfile(); }, async saveProfile() { await this.backendAuth('sendProfileData', { @@ -363,25 +363,21 @@ export default { await this.backendAuth('sendProfileData', data); await this.resetEditedValues(); }, - reloadData() { - this.getProfile(); - Backend.getSenderStats(this.address).then((stats) => { - this.userStats = stats; - }); + async reloadData() { + await Promise.all([ + this.reloadProfile(), + Backend.getSenderStats(this.address).then((stats) => { + this.userStats = stats; + }), + ]); }, - async getProfile() { - 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), + }; }, }, }; diff --git a/src/components/tipRecords/Author.vue b/src/components/tipRecords/Author.vue index 917fcd14f..27a1b657b 100644 --- a/src/components/tipRecords/Author.vue +++ b/src/components/tipRecords/Author.vue @@ -48,8 +48,7 @@ export default { }, }, async mounted() { - const profile = await Backend.getProfile(this.address); - this.name = profile ? profile.preferredChainName : null; + this.name = (await Backend.getProfile(this.address)).preferredChainName; }, }; diff --git a/src/components/tipRecords/TipPreview.vue b/src/components/tipRecords/TipPreview.vue index d0d04d076..4ec71d5fb 100644 --- a/src/components/tipRecords/TipPreview.vue +++ b/src/components/tipRecords/TipPreview.vue @@ -192,7 +192,8 @@ export default { return this.tip?.linkPreview?.title || ''; }, tipPreviewImage() { - return this.isPreviewToBeVisualized && this.tip.linkPreview.image !== null ? Backend.getTipPreviewUrl(this.tip.linkPreview.image) : ''; + return this.isPreviewToBeVisualized && this.tip.linkPreview.image !== null + ? Backend.getTipPreviewUrl(this.tip.linkPreview.image) : ''; }, isPreviewToBeVisualized() { return this.tip.linkPreview?.description || this.tip.linkPreview?.title; diff --git a/src/store/index.js b/src/store/index.js index c289ef018..738f50285 100644 --- a/src/store/index.js +++ b/src/store/index.js @@ -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', { @@ -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), }); } })); @@ -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) handleUnknownError(error); + return 0; + }); commit('updateBalance', balance); })(), dispatch('updateTokensBalanceAndPrice'), diff --git a/src/store/modules/backend.js b/src/store/modules/backend.js index ee8519e70..50421dfd5 100644 --- a/src/store/modules/backend.js +++ b/src/store/modules/backend.js @@ -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: { @@ -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) { @@ -120,7 +116,7 @@ export default { commit('setStats', { ...stats1, ...stats2, height }); }, async reloadPrices({ commit }) { - commit('setPrices', (await Backend.getPrice())?.aeternity); + commit('setPrices', (await Backend.getPrice()).aeternity); }, // eslint-disable-next-line consistent-return async callWithAuth({ diff --git a/src/utils/backend.js b/src/utils/backend.js index 7a91590db..b3bd109d8 100644 --- a/src/utils/backend.js +++ b/src/utils/backend.js @@ -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)}`); @@ -108,7 +88,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' }, @@ -129,7 +109,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}`);