我编写一个谷歌云函数来创建聊天室,用户根据自己的兴趣从移动应用程序向Firestore发送请求,然后触发函数读取Firestore中所有待处理的请求,直到找到与用户匹配的人。发生这种情况时,云函数会删除这两个请求并创建聊天室,但我的问题是,如果同时有多个用户发送请求,云函数会读取理论上应该已经删除的请求。这是我的代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.cargarPeticion = functions.firestore.document('/Requests/{id}').onCreate((snap, context) => {
const newValue = snap.data();
const uid = newValue.uid;
const age = newValue.age;
const sex = newValue.sex;
const manInterest = newValue.Hombres;
const womenInterest = newValue.Mujeres;
const loveInterest = newValue.Love;
const friendInterest = newValue.Friendship;
const timestamp = newValue.Timestamp;
const minAgeInterest = newValue.ageMin;
const maxAgeInterest = newValue.ageMax;
var ciclo = true;
db.collection('Requests').orderBy('Timestamp').get()
.then((snapshot) => {
try{
snapshot.forEach((doc) => {
var data = doc.data();
if(data.uid !== uid){
console.log("NUEVO");
console.log(doc.id, '=>', data.uid);
if(loveInterest === data.Love || friendInterest === data.Friendship){
if(data.age >= minAgeInterest &&
data.age <= maxAgeInterest &&
((sex === "H" && data.Hombres === "true") || (sex === "M" && data.Mujeres === "true"))){
if(age >= data.ageMin &&
age <= data.ageMax &&
((manInterest === "true" && data.sex === "H") || (womenInterest === "true" && data.sex === "M"))){
var arrayUsers = [uid, data.uid];
console.log("ID SALA");
console.log(uid.substring(0, 8) + data.uid.substring(0, 7) + doc.id.substring(0, 7));
db.collection('chatRoom').doc(uid.substring(0, 8) + data.uid.substring(0, 7) + doc.id.substring(0, 7)).set({
arrayUsers: arrayUsers,
uid1: uid,
uid2: data.uid,
chatRoomId : uid.substring(0, 8) + data.uid.substring(0, 7) + doc.id.substring(0, 7),
ultimoMensaje: '',
ultimoEscritorUid : '',
ultimoMensajeTiempo : 0
});
db.collection('Requests').doc(doc.id).delete();
db.collection('Requests').doc(snap.id).delete();
throw exception
}
}
}
}
});
}catch(exception){
console.log(exception);
}
return null;
})
.catch((err) => {
console.log('Error getting documents', err);
});
})
若要防止并发数据库更新创建不一致的数据集,需要使用事务来执行更新。使用事务时,允许第一个实例修改数据,并且对相同数据的任何冲突更新都会再次自动重试,直到没有冲突。