Last active
October 14, 2022 17:01
-
-
Save gabrielmlinassi/46fff09ea4abf9efcb43d1c3593843fc to your computer and use it in GitHub Desktop.
Node with multiple Requests with `request` lib. With Promises.
This file contains 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
const request = require("request"); | |
const baseUrl = "https://jsonmock.hackerrank.com/api/football_matches"; | |
async function myReq(url) { | |
return new Promise((resolve) => { | |
request.get(url.toString(), (err, response, body) => { | |
const data = JSON.parse(body); | |
resolve(data); | |
}); | |
}); | |
} | |
async function getTotalGoals(team, year) { | |
let pages = 1; | |
// get number of goals for when team home | |
const url = new URL(baseUrl); | |
url.searchParams.append("page", 1); | |
url.searchParams.append("year", year); | |
url.searchParams.append("team1", encodeURIComponent(team)); | |
let sum = 0; | |
await myReq(url).then((resp) => { | |
sum += resp.data.reduce((t, v) => t + +v.team1goals, 0); | |
pages = resp.data.total_pages; | |
}); | |
for (let page = 2; page < pages; page++) { | |
url.searchParams.set("page", page); | |
myReq(url).then((resp) => { | |
sum += resp.data.reduce((t, v) => t + +v.team1goals, 0); | |
}); | |
} | |
// get number of goals for when team is visiting | |
url.searchParams.set("page", 1); | |
url.searchParams.delete("team1"); | |
url.searchParams.append("team2", encodeURIComponent(team)); | |
await myReq(url).then((resp) => { | |
sum += resp.data.reduce((t, v) => t + +v.team2goals, 0); | |
pages = resp.data.total_pages; | |
}); | |
for (let page = 2; page < pages; page++) { | |
url.searchParams.set("page", page); | |
myReq(url).then((resp) => { | |
sum += resp.data.reduce((t, v) => t + +v.team1goals, 0); | |
}); | |
} | |
return sum; | |
} | |
(async () => { | |
console.log(await getTotalGoals("barcelona", 2011)); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment