简体   繁体   English

Cloud Function 在部署时不会保存到 Firestore

[英]Cloud Function does not save to Firestore when deployed

I have deployed a cloud function that loads an API and saves its contents to my Firestore database.我已经部署了一个云 function,它加载了一个 API 并将其内容保存到我的 Firestore 数据库中。 It is working perfectly when I run the cloud function on my local environment using the firebase emulators.当我使用 firebase 模拟器在本地环境中运行云 function 时,它运行良好。 However, when I have deployed the same function to the Google Cloud Platform, it fails to save the contents to Firestore although it loads the API successfully.但是,当我将相同的 function 部署到 Google Cloud Platform 时,它无法将内容保存到 Firestore,尽管它成功加载了 API。 What else could I have been missing from my setup?我的设置中还缺少什么?

Here is the code.这是代码。 I purposely redacted the API link.我故意编辑了 API 链接。

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

admin.initializeApp({
    credential: admin.credential.applicationDefault()
});

 exports.savePSEData = functions.https.onRequest((req, res) => {
    const url = <LINK REDACTED>;
    return new Promise((resolve, reject) => {

        axios
            .get(url)
            .then(response => {
                const date = response.data.as_of;
                for (var index in response.data.stock) {
                    var stock = response.data.stock[index]
                    createStockDocument(date, stock.symbol, stock.price.amount, stock.percent_change, stock.volume, callback => {
                        console.log(index)
                    })
                }
               return res.status(200).send("ok");
            })
            .catch(error => {
                console.log(error);
               return res.status(500).send(error);
            });
    })

});

function createStockDocument(date, symbol, amount, percentChange, volume, callback) {
    console.log("Creating temp package")
    const docRef = admin.firestore().doc(`${symbol}/${date}`);
    docRef.set({ 
        amount: amount,
        percent_change: percentChange,
        volume: volume
    })
    .then(docRef => {
        console.log('Document created')
        return callback(docRef)
    }).catch(error => {
        console.log(`Error trying to create document ${error}`)
        return callback(error);
    })

}

Your code is ignoring the promise returned by docRef.set().then(...).catch(...) .您的代码忽略了docRef.set().then(...).catch(...)返回的 promise 。 Calling then and catch does not fully handle the promise. catch just returns another promise that resolves asynchronously after the entire chain resolves.调用thencatch并没有完全处理catch只是返回另一个 promise,它在整个链解析后异步解析。 This means that your function is also sending the response to the client before Firestore has completed the write, which means it might never complete.这意味着您的 function 也在 Firestore 完成写入之前向客户端发送响应,这意味着它可能永远不会完成。 Functions are terminated immediately after the response is set. 设置响应后,功能将立即终止。

You should make createStockDocument return that promise from the chain, then make the caller of the function wait for it before sending the response.您应该让createStockDocument从链中返回 promise,然后让 function 的调用者在发送响应之前等待它。 Minimally:最低限度:

function createStockDocument(date, symbol, amount, percentChange, volume, callback) {
    console.log("Creating temp package")
    const docRef = admin.firestore().doc(`${symbol}/${date}`);
    return docRef.set(...).then(...)
}

I suggest not using catch here, and instead have the caller catcher any errors.我建议不要在这里使用 catch,而是让调用者捕捉器出现任何错误。

createStockDocument(...)
.then(() => res.status(200).send("ok"))
.catch(error => res.status(500).send(error))

I strongly suggest getting a firm grasp of how promises work, as they are crucial to writing effective code in Cloud Functions.我强烈建议牢牢掌握 promise 的工作原理,因为它们对于在 Cloud Functions 中编写有效代码至关重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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