首页 > 解决方案 > Cloud 函数不响应 Cloud Firestore 中的 onCreate

问题描述

我有一个 index.js 文件,其中包含以下内容:

const functions = require('firebase-functions');
const trackVote = require('./trackVote')
const admin = require('firebase-admin');
admin.initializeApp();

exports.trackVote = trackVote.handler;

然后我引用以下函数:

trackvote.js

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

exports.handler = functions.firestore.document('/Polls/{pollId}/responses/{userId}').onCreate((data, context) => {
           const answerSelected = data.data().answer;

           const answerRef = admin.firestore().doc(`Polls/${context.params.pollId}/answers/${answerSelected}`);
           const voteCountRef = admin.firestore().doc(`Polls/${context.params.pollId}`);

            return admin.firestore().runTransaction(t => {
                        return t.get(answerRef)
                            .then(doc => {
                                if (doc.data()) {
                                    t.update(answerRef, { vote_count: doc.data().vote_count + 1 });
                                }
                            })
                    }).then(result => {
                        return admin.firestore().runTransaction(t => {
                                    return t.get(voteCountRef)
                                        .then(doc => {
                                            if (doc.data()) {
                                                t.update(voteCountRef, {vote_count:doc.data().vote_count+1});
                                            }
                                        });
                                 });
                    });
    });

不幸的是,没有调用此方法,但是我知道我正在写入 Cloud Firestore 中的特定位置。我的 Firebase 仪表板中也没有任何日志。

以下是写入我的 Cloud Firestore 的代码:

    mPollQuestionRadioGroup.setOnCheckedChangeListener(new 
    RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        disableVoteButtons(group);
        Toast.makeText(getActivity().getApplicationContext(), R.string.vote_submitted_label, Toast.LENGTH_LONG).show();

        voteOnPoll((Integer) group.findViewById(checkedId).getTag());

        //TODO: add animation between between vote click and chart display
        mPollQuestionRadioGroup.setVisibility(View.INVISIBLE);
        mPollResults.setVisibility(View.VISIBLE);
    }

});

方法:

 private void voteOnPoll(int checkedRadioButtonIndex) {
        int selectedAnswerIndex = checkedRadioButtonIndex + 1;
        HashMap<String, Object> firebaseAnswer = new HashMap<>();
        firebaseAnswer.put("answer", selectedAnswerIndex);
        mStoreBaseRef.collection("Polls").document(pollID).collection("responses").document(mUserID).set(firebaseAnswer);
    }

当我在仪表板中检查 Cloud Firestore 时,我可以确认此位置已成功写入。

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


推荐阅读