Home > Blockchain >  Adding data to firestore database with firebase functions
Adding data to firestore database with firebase functions

Time:12-20


data i get from external api is not saved in firestore database

but the record I added as last name xxxxx is successful wait db.collection('coins').add({lastName: 'xxxxxxx'}) this works but the code below does not

exports.firestoreKaydet = functions.firestore
  .document("/users/{userId}")
  .onCreate(async (snap, context) => {
    await db.collection("coins").add({ lastName: "xxxxxxx" });

    fetch(
      "https://api.coinecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true"
    )
      .then((response) => response.json())
      .then(async (data) => {
        data.forEach(async (coin) => {
          await db.collection("coins").add({
            name: coin.name,
          });
        });
      })
      .catch((error) => {
        console.error(error);
      });
  });

CodePudding user response:

 const { request } = require('express');
 const admin = require('firebase-admin');
 const functions = require('firebase-functions');
 admin.initializeApp();
 const db = admin.firestore();


 exports.firestoreKaydet=functions.firestore.document('/users/{userId}')
      .onCreate(async (snap, context) => {


  const response = await 
   fetch('https://api.coingecko.com/api/v3/coins/markets? 
 vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true');

const data = response.json();;

 const promises = [];
 await data.forEach(async coin => {
    promises.push(db.collection('coins').add({
        name: coin.name
    }));
 });

 return Promise.all(promises)
 });

CodePudding user response:

You should not use async/await within a forEach() loop, see "JavaScript: async/await with forEach()" and "Using async/await with a forEach loop".

You can use Promise.all() as follows:

exports.firestoreKaydet = functions.firestore.document('/users/{userId}').onCreate(async (snap, context) => {
    
    try {
        
        // db shall be defined as admin.firestore()

        await db.collection('coins').add({ lastName: 'xxxxxxx' });

        const response = await fetch("https://api.coinecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true");

        const data = response.json();

        const promises = [];
        data.forEach(coin => {
            promises.push(db.collection('coins').add({
                name: coin.name
            }));
        });

        return Promise.all(promises);
        
    } catch (error) {
        console.error(error);
        return null;
    }
    
});

UPDATE: After helping you debugging, it appears that fetch was not installed. Install it in the functions directory as follows

npm install node-fetch

then put the line below in the index.js file:

import fetch from "node-fetch";
  • Related