I am making an app that should display live soccer data. For the back end, I get my data from an API and want to place this in Firebase's real-time database to allow for live data in the app. The data from the API already comes as JSON, so is there any way to utilize this?
The top level of the real-time database should be dates from a fixed interval, and under each date, I want to nest the JSON data from the API.
Below is how I am currently trying to insert into the real-time database using the set() method, though, nothing happens in its current state.
import { initializeApp } from "firebase/app";
import { getDatabase, ref, set } from "firebase/database";
import { getDates } from './dates.js';
import { getDataApi, getCurrentSeason } from './api_manager.js';
import { idList } from '../data/data.js';
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
const db = getDatabase();
function update() {
var startDate = new Date();
var season = getCurrentSeason().then(val => val);
var datesArr = getDates(startDate, 7);
datesArr.forEach(date => {
idList.forEach(id => {
const reference = ref(db, `${date}/${id}`);
var data = getDataApi(date, id, season);
set(reference, data);
});
});
}
update();
If it's of any interest, these are my methods for fetching the data from the API:
import fetch from 'node-fetch';
const options = {
method: 'GET',
headers: {
...
}
};
export async function getDataApi(date, leagueId, season) {
const url = `https://api-football-v1.p.rapidapi.com/v3/fixtures?date=${date}&league=${leagueId}&season=${season}`;
try {
let response = await fetch(url, options);
let json = await response.json();
return json['response'];
} catch (error) {
console.log("Error: " error);
}
}
export async function getCurrentSeason() {
const url = 'https://api-football-v1.p.rapidapi.com/v3/leagues?id=39¤t=true';
try {
let response = await fetch(url, options);
let json = await response.json();
return json['response'][0]['seasons'][0]['year'];
} catch (error) {
console.log("Error: " error);
}
}
CodePudding user response:
Your getCurrentSeason
and getDataApi
functions are marked as async
, yet you're not using await
when calling them. Even the one then()
call you have won't work, as all code that needs the value would have to be inside that then()
callback.
A simple approach:
async function update() {
var startDate = new Date();
var season = await getCurrentSeason(); //