Last active
March 3, 2019 06:37
-
-
Save theoperatore/ac73aded0ac2c390241e12833b531aac to your computer and use it in GitHub Desktop.
Get random game metadata via giant-bomb api for any platform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// depends on fetch, async/await (node 8.2.1+) | |
require('isomorphic-fetch'); | |
const getAllPlatforms = async apiKey => { | |
const rawResponse = await fetch(`http://www.giantbomb.com/api/platforms?api_key=${apiKey}&format=json&field_list=name,id`); | |
const response = await rawResponse.json(); | |
// check response.error === "OK" && repsonse.status_code === 1 | |
return response.results; | |
} | |
const findGameMaxForPlatform = async (apiKey, platform = 9) => { | |
const rawResponse = await fetch(`http://www.giantbomb.com/api/games?api_key=${apiKey}&format=json&platforms=${platform}&limit=1&field_list=id`); | |
const response = await rawResponse.json(); | |
// check response.error === "OK" && repsonse.status_code === 1 | |
// only interseted in the "number_of_total_results" | |
// mainly to help with random offsets | |
return response.number_of_total_results; | |
} | |
// find a game given a max and platform | |
const findRandomGame = async (apiKey, platform = 9, gameMax = 1764) => { | |
const offset = Math.round(Math.random() * gameMax + 1); | |
const rawResponse = await fetch(`http://www.giantbomb.com/api/games?api_key=${apiKey}&format=json&platforms=${platform}&limit=1&offset=${offset}`); | |
const response = await rawResponse.json(); | |
// check response.error === "OK" && repsonse.status_code === 1 | |
// but meh, that's for another person to do | |
// I just want the game! | |
return response.results[0]; | |
} | |
const getRandomGameForPlatform = async (apiKey, platformName) => { | |
const platforms = await getAllPlatforms(apiKey); | |
const platform = platforms.find(plat => plat.name === platformName) || { id: -1 }; | |
const maxGames = await findGameMaxForPlatform(apiKey, platform.id); | |
return await findRandomGame(apiKey, platform.id, maxGames); | |
} | |
// EXAMPLE: find random game gear game | |
getRandomGameForPlatform('abc123', 'Game Gear') | |
.then(console.log) | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment