Thursday, 11 May 2017

Can I clean up an API fetch using variables?

I'm fetching from an API and my code is so messy. I'm wondering if I can set a variable within .then() to clean it up?

    fetch.get(url)
.then(r => message.channel.send(`Win Rate: ${r.body.us.stats.competitive.overall_stats.win_rate}\nLevel: ${r.body.us.stats.competitive.overall_stats.level}\nPrestige: ${r.body.us.stats.competitive.overall_stats.prestige}\nWins: ${r.body.us.stats.competitive.overall_stats.wins}\nLosses: ${r.body.us.stats.competitive.overall_stats.losses}\nGames: ${r.body.us.stats.competitive.overall_stats.games}\nCompetitive Rank: ${r.body.us.stats.competitive.overall_stats.comprank}`));

Would be perfect if I could do something like this so I only have to have the massive chain of properties once:

var stats = r.body.us.stats.competitive.overall_stats

That way I could do something like

stats.level
stats.prestige

Etc.

Also, I would like to refer to those objects outside of the function, what would be the best way to do that? I've considered saving to a .json file but not sure how to go about it or if that's the best way.



via andrewb

No comments:

Post a Comment