I created a cloud function that fills a collection with the following fields: "IdConvite", "createdby", "ExpiresAt" and "coupleID". The function works well and fills correctly (I will show the prints and the function). However, when I go to another screen to make a query in the backend to search for this "createdby" (which is the uid of the authenticated user) it does not find it and comes back empty, leaving the entire screen gray (since I marked it not to bring anything if there is no match)
Segue a minha função em nuvem:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const crypto = require('crypto');
// Keep this commented as FlutterFlow recommends
//admin.initializeApp();
exports.criaConvite = functions.https.onCall(async (data, context) => {
try {
// This check is critical - ensure we have valid auth
if (!context.auth) {
return {
success: false,
errorMessage: 'Usuário não autenticado'
};
}
const userId = context.auth.uid;
// Generate invite code first
let inviteCode = crypto.randomInt(100000, 999999).toString();
// Check if code exists (simplified to reduce potential errors)
const snapshot = await admin.firestore()
.collection('convite')
.where('idConvite', '==', inviteCode)
.limit(1)
.get();
if (!snapshot.empty) {
// Try one more time if there's a collision
inviteCode = crypto.randomInt(100000, 999999).toString();
}
// Step 1: Create couple document
const coupleDoc = await admin.firestore().collection('couples').add({
user1ID: userId,
user2ID: null,
createdAt: admin.firestore.FieldValue.serverTimestamp()
});
console.log('Created couple document with ID:', coupleDoc.id);
// Step 2: Create invite document separately
await admin.firestore().collection('convite').doc(inviteCode).set({
idConvite: inviteCode,
createdBy: userId,
experiesAt: admin.firestore.Timestamp.fromDate(new Date(Date.now() + 86400000)),
coupleID: coupleDoc.id
});
console.log('Created invite document with code:', inviteCode);
// Step 3: Update user document
await admin.firestore().collection('users').doc(userId).update({
coupleID: coupleDoc.id
});
console.log('Updated user document');
return {
success: true,
inviteCode: inviteCode,
coupleID: coupleDoc.id
};
} catch (error) {
console.error('Error in criaConvite function:', error);
// Return structured error
return {
success: false,
errorMessage: error.message || 'Erro interno'
};
}
});