From 9faf3e5ebc3bf7cfb5eb5ee54876e158485edd44 Mon Sep 17 00:00:00 2001 From: anthony Date: Mon, 14 Feb 2022 09:12:53 +0100 Subject: [PATCH] Add API calls --- index.js | 80 +++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 65 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index 34ec7af..e99965a 100644 --- a/index.js +++ b/index.js @@ -2,26 +2,76 @@ import fastify from 'fastify'; // see axios doc on how to use it import axios from 'axios'; -const app = fastify({ logger: true }); - -app.post('/', async (req, res) => { - return { - message: `Welcome to Node Babel with ${ - req.body?.testValue ?? 'no testValue' - }`, - }; +const app = fastify({logger: true}); + +const CAT_API_ENDPOINT = "https://cat-fact.herokuapp.com"; +const CAT_FACTS_COUNT = 3; + +async function fetch3CatFacts() { + const uri = `${CAT_API_ENDPOINT}/facts/random?amount=${CAT_FACTS_COUNT}`; + try { + const response = await axios.get(uri); + return response.data.map(rep => rep.text); + } catch { + return null; + } +} + +const FOX_API_ENDPOINT = 'https://randomfox.ca/floof'; + +async function fetchFowImage() { + try { + const response = await axios.get(FOX_API_ENDPOINT); + return response.data.image; + } catch { + return null; + } +} + +const DAYS_OFF_API_ENDPOINT = "https://date.nager.at" + +async function fetchDaysOfPerCountry(country) { + + if (country) { + return null; + } + + const year = new Date().getFullYear() + const uri = `${DAYS_OFF_API_ENDPOINT}/api/v3/PublicHolidays/${year}/${country}` + try { + const response = await axios.get(uri); + return response.data; + } catch { + return null; + } +} + +app.post('/', async (req, _res) => { + + const countryCode = req.body?.countryCode; + const [foxPicture, catFacts, holidays] = Promise.all([ + fetchFowImage(), + fetch3CatFacts(), + fetchDaysOfPerCountry(countryCode) + ]) + + return { + foxPicture, + catFacts, + holidays + }; }); // Only used for dev server, do not remove -app.head('/', () => ({ ping: 'pong' })); +app.head('/', () => ({ping: 'pong'})); // Run the server! const start = async () => { - try { - await app.listen(5000); - } catch (err) { - app.log.error(err); - process.exit(1); - } + try { + await app.listen(5000); + } catch (err) { + app.log.error(err); + process.exit(1); + } }; start();