I'm studying firebase cloud function and trying to register a user at firebase auth using javascript and the cloud functions. What I want to do is to send the data to the cloud function, return data from the cloud function, and then use it on the web app. How can I do it? Here are both codes:
Javascript sends values, which is working well:
const sendData = firebase.functions().httpsCallable('registerUser');
sendData({
email: userEmail,
password: userPassword
});
and here, my cloud function, which is registering the user correctly.
exports.registerUser = functions.https.onCall((data, context) => {
const userEmail = data.email;
const userPassword = data.password;
admin.auth().createUser({
email: userEmail,
emailVerified: false,
password: userPassword,
displayName: "name",
photoURL: "...",
disabled: false
})
.then(() => {
//want to return messages if succeed or not
}) });
I want to send the messages from the cloud function and then get it on my javascript code. How can I do it?
As explained in the documentation, to "send data back to the client, return data that can be JSON encoded" and to return errors you should "throw (or return a Promise rejected with) an instance of functions.https.HttpsError
".
exports.registerUser = functions.https.onCall((data, context) => {
const userEmail = data.email;
const userPassword = data.password;
return admin.auth().createUser({ // See the return here
email: userEmail,
emailVerified: false,
password: userPassword,
displayName: "name",
photoURL: "...",
disabled: false
})
.then(userRecord => {
//want to return messages if succeed or not
return {
result: 'success'
};
})
.catch(error => {
throw new functions.https.HttpsError('invalid-argument', 'message');
})
});
You may use different error codes, depending on the type of error. See the doc.
Then, in the client, you need to do as follows:
sendData({
email: userEmail,
password: userPassword
}).then(function(response) {
// Read result of the Cloud Function.
var result = response.data.result;
// ...
}).catch(function(error) {
// Getting the Error details.
var code = error.code;
var message = error.message;
var details = error.details;
// ...
});