简体   繁体   中英

Firebase - Can I set() existing JSON into Real-Time Database?

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&current=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);
    }

}

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(); // 👈
    var datesArr = getDates(startDate, 7);

    datesArr.forEach(date => {
        idList.forEach(id => {
            const reference = ref(db, `${date}/${id}`);
            var data = await getDataApi(date, id, season); // 👈
            set(reference, data);
        });
    });
}

Note that this code will still continue to run after your update(); call returns, so check if your process is terminated prematurely.

In general, I recommend reading up on asynchronous operations in JavaScript, as you'll keep encountering that. Some more good sources for that:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM