core: user_create: add optimistic loop

This commit is contained in:
undefined committed 2024-01-28 02:32:43 +08:00
1 parent 6b759cbe63
commit a863a6501e
1 file changed
+9 -3
+9 -3
View File
@@ -312,12 +312,16 @@ class UserModel {
mail: string, uname: string, password: string,
uid?: number, regip: string = '127.0.0.1', priv: number = system.get('default.priv'),
) {
const salt = String.random();
let autoAlloc = false;
if (typeof uid !== 'number') {
const [udoc] = await coll.find({}).sort({ _id: -1 }).limit(1).toArray();
uid = Math.max((udoc?._id || 0) + 1, 2);
autoAlloc = true;
}
const salt = String.random();
while (true) { // eslint-disable-line no-constant-condition
try {
// eslint-disable-next-line no-await-in-loop
await coll.insertOne({
_id: uid,
mail,
@@ -334,14 +338,16 @@ class UserModel {
priv,
avatar: `gravatar:${mail}`,
});
return uid;
} catch (e) {
if (e?.code === 11000) {
// Duplicate Key Error
throw new UserAlreadyExistError(Object.values(e?.keyValue || {}));
}
throw e;
if (!autoAlloc || JSON.stringify(e.keyPattern) !== '{"_id":1}') throw e;
}
uid++;
}
return uid;
}
@ArgMethod