I recently created a function in vanilla JS called fetch to retrieve data from an API. Now, I am looking to send this data to my MongoDB database using Node.js. It's a bit chaotic right now as my friend is handling the backend while I focus on the frontend. We are in the process of combining our code and I'm not quite sure what to do with this 'req' argument in the create function. Any help would be greatly appreciated. Thank you.
const Match = require('../db/models/match');
class MatchController {
async showMatches(req, res) {
const matches = await Match.find();
res.status(200).json(matches); //parsuje dane na JSON
console.log('show');
}
async create(req, res) {
const match = getDataForSheduleCJS(nameLeague).then(resp => {
const matchObject = new Match({
leagueName: resp.competition.name,
date: resp.utcDate.slice(0, 10),
awayTeam: resp.awayTeam.name,
homeTeam: resp.homeTeam.name,
scoreHomeTeam: resp.score.fullTime.homeTeam,
scoreAwayTeam: resp.score.fullTime.awayTeam,
});
return matchObject;
});
// const match = new Match({
// leagueName: 'Bundes'
// });
try {
console.log(match);
await match.save();
//res.status(201).json(match);
} catch (e) {
console.log('error');
res.status(422).json({
errors: e.errors
});
}
}
}
module.exports = new MatchController();
const getDataForSheduleCJS = () => {
fetch(`https://api.football-data.org/v2/competitions/PL/matches`, {
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': personalToken
}}).then(resp => resp.json())
// .then(data => data)
.catch((error) => {
alert("Wystąpił problem z danymi")
console.error('Error:', error);
});
}
const express = require('express');
const router = new express.Router(); //zmieniamy nazwy z app.get na router.get
const MatchController = require('../controllers/match-controller');
router.get('/matches', MatchController.showMatches);
router.post('/matches', MatchController.create);
module.exports = router;