I'm trying to write a Firebase Cloud Function that does the following, using the Firebase Admin SDK:
- Creates user with email/password.
- Creates a Firestore doc, with reference the newly created UID.
- Returns a Firebase JWT token to the client, if 1 & 2 are successful.
The code I have so far is below:
exports.createUser = functions.https.onCall((data, context) => {
return admin
.auth()
.createUser({
email: data.email,
password: data.password,
phoneNumber: data.number,
})
.then((user) => {
return admin
.firestore()
.collection("collectionName")
.doc(user.uid)
.set({});
})
.catch((error) => {
console.log("Error creating new user:", error);
});
});
What I'm struggling with is the next .then()
in the chain, to return the JWT token. I'm aware of the actual Admin SDK code to return a JWT, but I'm not sure how I can access the new user's properties in multiple .then()
s, while also returning a promise (which I think is necessary for proper function termination?)
How can I add another .then()
that has access to user.uid
and also ensures the function instance is not prematurely terminated?
CodePudding user response:
You can simply use a variable as shown below:
exports.createUser = functions.https.onCall((data, context) => {
let userObject;
return admin
.auth()
.createUser({
email: data.email,
password: data.password,
phoneNumber: data.number,
})
.then((user) => {
userObject = user
return admin
.firestore()
.collection("collectionName")
.doc(user.uid)
.set({});
})
.then(() => {
const user = userObject;
// Do whathever you want with user
await function(user)
// Don't forget to return data that can be JSON encoded, see the doc: https://firebase.google.com/docs/functions/callable#sending_back_the_result
// In your case the JWT Object I guess
return ...
})
.catch((error) => {
console.log("Error creating new user:", error);
// See the doc: https://firebase.google.com/docs/functions/callable#handle_errors
});
});
If you use async/await
it is even easier:
exports.createUser = functions.https.onCall(async (data, context) => {
const user = await admin
.auth()
.createUser({
email: data.email,
password: data.password,
phoneNumber: data.number,
});
await admin
.firestore()
.collection("collectionName")
.doc(user.uid)
.set({});
// Do whathever you want with user
await function(user)
return ...
});