From f954d445fbfbdc6b11e1f93ba2106faf8a63b989 Mon Sep 17 00:00:00 2001 From: MTLantoine Date: Wed, 17 Feb 2021 21:03:42 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20add=20API=20requests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.js | 44 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index a282a8e..f1c8f6d 100644 --- a/index.js +++ b/index.js @@ -4,13 +4,45 @@ import axios from 'axios'; const app = fastify({ logger: true }); -app.get('/', async (req, res) => { +// Request +const request = async (method, url, target = null) => { + try { + const result = await axios({ + method: method, + url: url, + }) + return target ? result.data[target] : result.data; + } catch(error) { + return null; + } +} + +// Get cat +const getCats = async () => { + return await request('get', 'https://cat-fact.herokuapp.com/facts/random?amount=3'); +} + +// Get fox +const getFox = async () => { + return await request('get', 'https://randomfox.ca/floof/', 'image'); +} + +// Get holidays +const getHollidays = async (cp) => { + return await request('get', `https://date.nager.at/api/v2/publicholidays/2021/${cp}`); +} + +app.post('/', async (req, res) => { + const fox = await getFox(); + const cats = await getCats(); + const holidays = await getHollidays(req.body.countryCode); + return { - message: `Welcome to Node Babel with ${ - req.body?.testValue ?? 'no testValue' - }`, - }; -}); + foxPicture: fox, + catFacts: cats === null ? cats : cats.map(cat => cat.text), + holidays: holidays, + }; +}); // Run the server! const start = async () => {