简体   繁体   English

Firebase Cloud Functions - 如何调用另一个函数并返回对象

[英]Firebase Cloud Functions - How to call another function and return object

I've created a callable function from my Angular component.我已经从我的 Angular 组件创建了一个可调用函数。 My angular component calls the createUser function and successfully returns the userRecord value.我的角度组件调用createUser函数并成功返回userRecord值。

However, what I would like to do is call another cloud function called createUserRecord .但是,我想做的是调用另一个名为createUserRecord的云函数。 I'm not overly familiar with promises and what needs to be returned where in this particular scenario.我不太熟悉承诺以及在这种特定情况下需要返回的内容。

Below are my two cloud functions.下面是我的两个云函数。 How would I go about calling createUserRecord upon the success of createUser ?我将如何在createUser createUserRecord

export const createUser = functions.https.onCall(async (data, context) => {
    console.log('data = ', data);
    return admin.auth().createUser({
        email: data.email,
        password: data.password,
    }).then(function (userRecord) {
        return userRecord
    })
        .catch(function (error) {
            return error;
            console.log('Error creating new user:', error);
        });
});




export const createUserRecord = functions.auth.user().onCreate((user, context) => {
    const userRef = db.doc(`users/${user.uid}`);
    return userRef.set({
        email: user.displayName,
        createdAt: context.timestamp,
        nickname: 'bubba',
    })
});

Update更新

This is a version I produced where I merged the two functions together.这是我制作的一个版本,我将这两个功能合并在一起。 This does produce the expected result of creating and account and then writing to firestore.这确实会产生创建和帐户然后写入 firestore 的预期结果。 However, it does feel a little 'off' due to the fact that it doesn't return a value to the client.但是,由于它没有向客户端返回值,因此确实感觉有点“不对劲”。

export const createUser = functions.https.onCall(async (data, context) => {
    console.log('data = ', data);
    return admin.auth().createUser({
        email: data.email,
        password: data.password,
    }).then(function (userRecord) {
        const userRef = db.doc(`users/${userRecord.uid}`);
        return userRef.set({
            email: data.email,
            name: data.name,
        })
    })
        .catch(function (error) {
            return error;
            console.log('Error creating new user:', error);
        });
});

Angular Callable Function角度可调用函数

The sanitizedMessage console log will return undefined. sanitizedMessage控制台日志将返回未定义。

addUser() {

    const createUser = firebase.functions().httpsCallable('createUser');

    const uniquePassword = this.afs.createId();

    createUser({
      email: this.userForm.value.email,
      password: uniquePassword,
      name: this.userForm.value.name,
    }).then((result) => {
      // Read result of the Cloud Function.
      var sanitizedMessage = result.data.text;
      console.log('sanitizedMessage = ', sanitizedMessage);
    }).catch((error) => {
      var code = error.code;
      var message = error.message;
      var details = error.details;
      console.log('error = ', error);
    });
  }

If you want to create a record in Firestore upon user creation you can very well do that within a unique Cloud Function.如果您想在创建用户时在 Firestore 中创建一条记录,您可以在一个独特的 Cloud Function 中很好地做到这一点。 The following code will do the trick, making the assumption that you want to write to the users Firestore collection.下面的代码可以解决这个问题,假设您要写入users Firestore 集合。

const FieldValue = require('firebase-admin').firestore.FieldValue;

...
export const createUser = functions.https.onCall((data, context) => {
  console.log('data = ', data);
  return admin
    .auth()
    .createUser({
      email: data.email,
      password: data.password
    })
    .then(userRecord => {
      return admin.firestore().collection('users')
        .doc(userRecord.uid)
        .set({
          email: userRecord.displayName,
          createdAt: FieldValue.serverTimestamp(),
          nickname: 'bubba'
        });
    })
    .then(() => {
      return {
        result: 'Success'
      };
    })
    .catch(error => {
      //Look at the documentation for Callable Cloud Functions to adapt this part:
      //https://firebase.google.com/docs/functions/callable?authuser=0
    });
});

"Is there any particular reason not to chain functions in CF's?"? “有什么特别的理由不在 CF 中链接函数吗?”?

As explained in the documentation , "Cloud Functions can be associated with a specific trigger".文档中所述,“云功能可以与特定触发器相关联”。 You can "chain" Cloud Functions by creating the corresponding triggers, for example, creating a doc in Firestore in one CF (Callable Function for example), that would trigger another CF that respond to a Firestore trigger).您可以通过创建相应的触发器来“链接”Cloud Functions,例如,在一个 CF 的 Firestore 中创建一个文档(例如可调用函数),这将触发另一个响应 Firestore 触发器的 CF。 Having said that, in most cases you can probably cover a lot of needs in a unique Cloud Function, by chaining promises, instead of chaining Cloud Functions .话虽如此,在大多数情况下,通过链接 promises 而不是链接 Cloud Functions,您可能可以在一个独特的 Cloud Function 中满足很多需求

Finally, I would not recommend to call an HTTP Cloud Function from within a Cloud Function because (IMHO) HTTP Cloud Functions are more designed to be called by an external consumer (I even don't know if this would work).最后,我不建议从云函数内部调用 HTTP 云函数,因为(恕我直言)HTTP 云函数更适合由外部消费者调用(我什至不知道这是否可行)。

It would be interesting to have Firebasers opinion on that! Firebases 对此有意见会很有趣!

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

相关问题 如何从 Firebase 云调用异步函数 Function - How to call async functions from a Firebase Cloud Function flutter firebase 云函数模拟器,随叫随到的函数不起作用 - flutter firebase cloud function emulator, on call functions not working Firebase 在手机上如何验证对云 function 的调用? - Firebase on mobile how to authenticate call to cloud function? Firebase Cloud Functions - 如何在 multiple.then() 方法中使用相同的返回值 - Firebase Cloud Functions - How to use same return value in multiple .then() methods 如何从 firebase 云 function 返回数据并返回异步响应? - How to return data from firebase cloud function and return async response? 云功能 | 登录 Firebase 并返回访问令牌 - Cloud Functions | Login into Firebase and return access token 在 Firebase 调用 setTimeout Cloud Functions onCreate - Call setTimeout at Firebase Cloud Functions onCreate 如何从统一中调用 firebase 示例云 function? - how to call a firebase sample cloud function from unity? Firebase 云function嵌套条件下如何满足返回promise? - How to satisfy requirement to return promise in Firebase cloud function with nested conditions? NodeJs function 在 Firebase 云函数中无法按预期工作 - NodeJs function not working as expected in Firebase Cloud functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM