Reputation: 1783
I am calling the Functions function to get user information, but it returns null. Please tell me the solution.
workspace/functions/src/index.ts
exports.getUser = functions.https.onCall((data, context) => {
admin.database().ref(`user/${data.userId}`)
.on('value', (snapshot) => {
if (snapshot) return snapshot.val();
});
});
workspace/src/app/sample.component.ts
firebase.functions().httpsCallable('getUser')({
userId: profile.userId
}).then(data => {
console.log(data);
}).catch(error => {
alert(error);
});
Upvotes: 0
Views: 228
Reputation: 317808
First of all, you should be using once()
instead of on()
for your query. on() sets up a persistent listener, which is not good in Cloud Functions, because it might leak the listener and cost you money. once() performs a single query and returns a promise that you can work with.
Second, you should return a promise from your function that resolves with the data you want to return to the client. This is required by callable type triggers. Right now, you're returning nothing from the top-level function.
Third, you should return a value in every code path through your function.
exports.getUser = functions.https.onCall((data, context) => {
return admin.database().ref(`user/${data.userId}`).once('value')
.then(snapshot => {
if (snapshot) {
return snapshot.val();
}
else {
// indicates that there was no data for the userId
return null;
}
});
});
Upvotes: 1
Reputation: 80944
You're not returning anything in your https callable, add a return:
exports.getUser = functions.https.onCall((data, context) => {
return admin.database().ref(`user/${data.userId}`)
.on('value', (snapshot) => {
if (snapshot) return snapshot.val();
});
});
Upvotes: 2