Browse Source

add API requests

main
MTLantoine 5 years ago
parent
commit
f954d445fb
  1. 44
      index.js

44
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 () => {

Loading…
Cancel
Save