云函数onCall-如何返回对象

时间:2020-03-29 17:00:57

标签: javascript angular firebase google-cloud-firestore google-cloud-functions

我正在尝试读取Google云函数onCall函数的返回值,但我一直读为null。

这是我的角度代码:

const callable = this.angularFireFunctions.httpsCallable('createEvent');
callable(this.formGroup.value).toPromise()
.then((next) => {
  console.log(next); //function succeeds but returned null
})
.catch((err) => {
  console.log(err);
})

我定义了以下云功能。一切都捆绑在一个事务中。

export const createEvent = functions.https.onCall((data: any, context: CallableContext) : any | Promise<any> =>
{
    const user_DocumentReference = db.collection('users').doc(context.auth?.uid);
    const event_DocumentReference = db.collection('events').doc();

    db.runTransaction((transaction: FirebaseFirestore.Transaction) =>
    {
        return transaction.getAll(user_DocumentReference)
        .then((documentSnapshots: FirebaseFirestore.DocumentSnapshot<any>[]) =>
        {
            const user_DocumentSnapshot = documentSnapshots[0].data();

            if (typeof user_DocumentSnapshot === 'undefined')
            {
                // return some error message json object
            }

            transaction.create(event_DocumentReference,
            {
                //json object
            });

            //return success object with few attributes
        })
        .catch((firebaseError: FirebaseError) =>
        {
            //return some error message json object
        }
    });
});

如何返回json对象作为保证? 我已经尝试了以下方法,但无济于事:

return Promise.resolve({ json object });
return Promise.reject({ json object });

1 个答案:

答案 0 :(得分:1)

您的顶级函数应返回一个承诺,该承诺将与数据一起解析以发送给客户端。从事务处理程序返回该值还不够。您还需要在顶层获得回报。从此开始:

return db.runTransaction(transaction => { ... })

从API文档中可以看到,runTransaction返回事务处理程序(或“ updateFunction”)返回的承诺。