1

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);
      });
  });
ChazUK
  • 744
  • 4
  • 26
Yusuf Brly
  • 49
  • 1
  • 5

2 Answers2

0

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";
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • thanks but same problem persists – Yusuf Brly Dec 19 '22 at 15:01
  • Do you see any error in the Google Cloud Logging console? In addition there was a copy/paste error in my answer: it should be `promises.push(...)` and not `p.push(...)`. – Renaud Tarnec Dec 19 '22 at 15:29
  • the error does not appear and the firestore database is empty – Yusuf Brly Dec 19 '22 at 15:57
  • How do you define `db`? Can you show your entire `index.js` file , with the module imports at the top. – Renaud Tarnec Dec 19 '22 at 16:02
  • now i added all index.js – Yusuf Brly Dec 19 '22 at 16:29
  • db.collection('coin').add({ last name: 'xxxxxxx' }); Do you understand why this works and why the other code does not? – Yusuf Brly Dec 19 '22 at 16:33
  • So the Cloud Function correctly writes to Firestore. What do you get if you add `console.log(JSON.stringify(response.json()));`. Where do you look for errors? – Renaud Tarnec Dec 19 '22 at 16:34
  • firebase-debug.log doesn't show any errors and terminal doesn't show any errors either – Yusuf Brly Dec 19 '22 at 16:38
  • But where do you look to see the errors? You need to use the Google Cloud Console: https://console.cloud.google.com/logs/query – Renaud Tarnec Dec 19 '22 at 16:40
  • resource.type="cloud_function" resource.labels.function_name="firestoreKaydet" resource.labels.region="us-central1" { insertId: "tp2lv6f7o1sv2" labels: {1} logName: "projects/borsa-app-f6921/logs/cloudfunctions.googleapis.com%2Fcloud-functions" receiveTimestamp: "2022-12-19T16:39:30.247959964Z" resource: {2} severity: "DEBUG" textPayload: "Function execution took 1388 ms, finished with status: 'error'" timestamp: "2022-12-19T16:39:29.966611847Z" trace: "projects/borsa-app-5" } – Yusuf Brly Dec 19 '22 at 16:50
  • there doesn't seem to be anything wrong here – Yusuf Brly Dec 19 '22 at 16:54
  • "Function execution took 1388 ms, finished with status: 'error'" => This is an error. Can you debug with adding `console.log(JSON.stringify(response.json()));`to see what the fetch call returns? – Renaud Tarnec Dec 19 '22 at 17:12
  • I'm a bit of a novice at this, I couldn't see where the log is written – Yusuf Brly Dec 19 '22 at 17:26
  • firebase functions:log --only firestore by running save command in Terminal D 2022-12-19T15:53:28.573032032Z D firestoreSave: Function execution started 2022-12-19T15:53:28.658742Z ? firestoreSave: ReferenceError: fetch is not defined – Yusuf Brly Dec 19 '22 at 17:40
  • I learned something new thanks to you – Yusuf Brly Dec 19 '22 at 17:55
  • okkkkkkkkkkkkkk – Yusuf Brly Dec 19 '22 at 18:07
0
 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)
 });
Yusuf Brly
  • 49
  • 1
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 21 '22 at 04:38