每当我捕捉到错误并在catch块仍然运行后通过代码从函数返回时,我都会遇到问题。这是我使用的两个功能:
usernameTaken: async (username) => {
const user = await firebase.firestore().collection("uniqueUsers").doc(username).get();
if (user.exists) {
alert("Username is taken. Try again with another username.");
throw new Error('Username is taken. Try again with another username.');
}
},
changeUsername: async (currentUsername, newUsername) => {
try {
var user = Firebase.getCurrentUser();
Firebase.usernameTaken(newUsername);
} catch (err) {
alert(err.message);
return;
}
await db.collection('uniqueUsers').doc(currentUsername).delete();
await db.collection("users").doc(user.uid).update({username: newUsername});
await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});
alert("Congratulations! You have successfully updated your username.");
}
我非常感谢对这个问题的任何帮助,因为我已经挣扎了两天多了,似乎找不到解决方案。
在原始代码中,usernameTaken()
承诺是浮动的,因为您没有使用await
。因为它是浮动的,所以catch()
处理程序永远不会捕捉到它的错误。
changeUsername: async (currentUsername, newUsername) => {
try {
const user = Firebase.getCurrentUser();
/* here -> */ await Firebase.usernameTaken(newUsername);
} catch (err) {
alert(err.message);
return;
}
/* ... other stuff ... */
}
附加点
usernameTaken
应返回布尔值
您应该更改usernameTaken
以返回布尔值。这可以说比使用alert()
(它会阻止代码的执行(或抛出错误要好。
usernameTaken: async (username) => {
const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
return usernameDoc.exists; // return a boolean whether the doc exists
}
安全地声明和发布用户名
根据您当前的代码,您没有任何保护措施来防止有人出现,他们只是删除了您数据库中的任何用户名,或者声称了从您上次检查其可用性到您致电set()
获取新用户名之间使用的用户名。您应该保护数据库的安全,以便用户只能写入自己的用户名。
将所有者的ID添加到文档中:
"/uniqueUsers/{username}": {
username: "username",
uid: "someUserId"
}
这样就可以将编辑/删除锁定到拥有该用户名的用户。
service cloud.firestore {
match /databases/{database}/documents {
match /uniqueUsers/{username} {
// new docs must have { username: username, uid: currentUser.uid }
allow create: if request.auth != null
&& request.resource.data.username == username
&& request.resource.data.uid == request.auth.uid
&& request.resource.data.keys().hasOnly(["uid", "username"]);
// any logged in user can get this doc
allow read: if request.auth != null;
// only the linked user can delete this doc
allow delete: if request.auth != null
&& request.auth.uid == resource.data.uid;
// only the linked user can edit this doc, as long as username and uid are the same
allow update: if request.auth != null
&& request.auth.uid == resource.data.uid
&& request.resource.data.diff(resource.data).unchangedKeys().hasAll(["uid", "username"]) // make sure username and uid are unchanged
&& request.resource.data.diff(resource.data).changedKeys().size() == 0; // make sure no other data is added
}
}
}
原子式更新数据库
你修改数据库的方式可能会损坏数据库。你可以删除旧用户名,然后无法更新当前用户名,这意味着你永远不会链接新用户名。要解决此问题,您应该使用批处理写入将所有这些更改一起应用。如果任何一个失败了,什么都不会改变。
await db.collection("uniqueUsers").doc(currentUsername).delete();
await db.collection("users").doc(user.uid).update({username: newUsername});
await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});
成为
const db = firebase.firestore();
const batch = db.batch();
batch.delete(db.collection("uniqueUsers").doc(currentUsername));
batch.update(db.collection("users").doc(user.uid), { username: newUsername });
batch.set(db.collection("uniqueUsers").doc(newUsername), { username: newUsername });
await batch.commit();
用户名应不区分大小写
您当前的用户名区分大小写,如果您希望用户键入/写出其个人资料的URL,则不建议使用这种方法。考虑"example.com/MYUSERNAME"
、"example.com/myUsername"
和"example.com/myusername"
如何都是不同的用户。如果有人在一张纸上潦草地写下他们的用户名,你会希望所有这些都进入同一用户的个人资料。
usernameTaken: async (username) => {
const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username.toLowerCase()).get();
return usernameDoc.exists; // return a boolean whether the doc exists
},
changeUsername: async (currentUsername, newUsername) => {
const lowerCurrentUsername = currentUsername.toLowerCase();
const lowerNewUsername = newUsername.toLowerCase();
/* ... */
return lowerNewUsername; // return the new username to show success
}
结果
将这些结合在一起,得出:
usernameTaken: async (username) => {
const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
return usernameDoc.exists; // return a boolean
},
changeUsername: async (currentUsername, newUsername) => {
const user = Firebase.getCurrentUser();
if (user === null) {
throw new Error("You must be signed in first!");
}
const taken = await Firebase.usernameTaken(newUsername);
if (taken) {
throw new Error("Sorry, that username is taken.");
}
const lowerCurrentUsername = currentUsername.toLowerCase();
const lowerNewUsername = newUsername.toLowerCase();
const db = firebase.firestore();
const batch = db.batch();
batch.delete(db.collection("uniqueUsers").doc(lowerCurrentUsername));
batch.update(db.collection("users").doc(user.uid), {
username: lowerNewUsername
});
batch.set(db.collection("uniqueUsers").doc(lowerNewUsername), {
username: lowerNewUsername,
uid: user.uid
});
await batch.commit();
return lowerNewUsername;
}
// elsewhere in your code
changeUsername("olduser", "newuser")
.then(
(username) => {
alert("Your username was successfully changed to @" + username + "!");
},
(error) => {
console.error(error);
alert("We couldn't update your username!");
}
);
注意:如果您使用上述所有建议(如安全规则(,batch.commit()
失败的预期方式之一是,如果有人在当前用户之前使用用户名。如果您遇到权限错误,假设有人在您之前使用了该用户名。
如果您的值为空或未定义,请尝试此检查,并在尝试块中抛出一些错误,例如
cosnt user = Firebase.getCurrentUser();
const name = Firebase.usernameTaken(newUsername);
// throwing error
if(name == "") throw "is empty";
await db.collection('uniqueUsers').doc(currentUsername).delete();