简体   繁体   中英

Pub Sub Cloud Function - Async Await

Trying to accomplish the following via a scheduled Firebase Function:

  1. Fetch Firestore Collection
  2. Delete Collection
  3. Make Get Request to External API
  4. Write Get Request results to Firestore Collection.

The function is failing to deploy. Error logs only say {"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code.

When I run the emulator suite locally, I get no errors, but the DB does not update.

I'm getting a linting error on the "=>" that's attached to the "onRun" method. Not sure if this is a code problem or an ESLint problem for ES6 in Firebase Functions.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');

admin.initializeApp();
const db = admin.firestore();

exports.scheduledFunction = functions.pubsub
    .schedule("every 2 minutes")
    .timeZone("America/New_York")
    .onRun(async (context) => {

      try {

        const querySnapshot = await db.collection("my_collection").get();
        console.log(querySnapshot.docs)
        const promises = querySnapshot.docs.map(doc => db.collection("my_collection").doc(doc.id).delete());

        await Promise.all(promises);

        const options = {
          "method": "get",
          "url": "www.myUrl.com",
          "headers": {
            "Cookie": "...",
          },
        };

        const axiosResponse = await axios(options);
        const apiResponse = JSON.parse(axiosResponse.data);
        const parsedResponse = apiResponse["news_results"];

        const docCreationPromises = parsedResponse.map(response => db.collection("my_collection").add(parsedResponse))

        await Promise.all(docCreationPromises);

        return null;

      } catch (error) {
        console.log(error);
        return null;
      }

    });

For the ESLint issue with => , try setting the ecmaVersion to 8 in your ESLint config.

module.exports = {
  root: true,
  env: {
    es6: true,
    node: true,
  },
  extends: [
    "eslint:recommended",
    "google",
  ],
  parserOptions: {
    ecmaVersion: 8
  }
};

When I run the emulator suite locally, I get no errors, but the DB does not update.

Are you using Firestore emulator? If yes, then data will be added there and not in production so you can see the data in emulator only.

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