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 committed Jul 7, 2021
1 parent 749858e commit 1a442e6
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 62 deletions.
34 changes: 15 additions & 19 deletions src/components/UserInfo.vue
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ export default {
},
async resetEditedValues() {
this.editMode = false;
await this.getProfile();
await this.reloadProfile();
},
async saveProfile() {
await this.backendAuth('sendProfileData', {
Expand All @@ -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),
};
},
},
};
Expand Down
3 changes: 1 addition & 2 deletions src/components/tipRecords/Author.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},
};
</script>
Expand Down
3 changes: 2 additions & 1 deletion src/components/tipRecords/TipPreview.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 6 additions & 10 deletions src/store/index.js
Original file line number Diff line number Diff line change
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) handleUnknownError(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 @@ -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({
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 @@ -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' },
Expand All @@ -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}`);
Expand Down

0 comments on commit 1a442e6

Please sign in to comment.