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
+30 -24
+30 -24
View File
@@ -312,36 +312,42 @@ class UserModel {
mail: string, uname: string, password: string, mail: string, uname: string, password: string,
uid?: number, regip: string = '127.0.0.1', priv: number = system.get('default.priv'), 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') { if (typeof uid !== 'number') {
const [udoc] = await coll.find({}).sort({ _id: -1 }).limit(1).toArray(); const [udoc] = await coll.find({}).sort({ _id: -1 }).limit(1).toArray();
uid = Math.max((udoc?._id || 0) + 1, 2); uid = Math.max((udoc?._id || 0) + 1, 2);
autoAlloc = true;
} }
try { const salt = String.random();
await coll.insertOne({ while (true) { // eslint-disable-line no-constant-condition
_id: uid, try {
mail, // eslint-disable-next-line no-await-in-loop
mailLower: handleMailLower(mail), await coll.insertOne({
uname, _id: uid,
unameLower: uname.trim().toLowerCase(), mail,
hash: pwhash(password.toString(), salt), mailLower: handleMailLower(mail),
salt, uname,
hashType: 'hydro', unameLower: uname.trim().toLowerCase(),
regat: new Date(), hash: pwhash(password.toString(), salt),
ip: [regip], salt,
loginat: new Date(), hashType: 'hydro',
loginip: regip, regat: new Date(),
priv, ip: [regip],
avatar: `gravatar:${mail}`, loginat: new Date(),
}); loginip: regip,
} catch (e) { priv,
if (e?.code === 11000) { avatar: `gravatar:${mail}`,
// Duplicate Key Error });
throw new UserAlreadyExistError(Object.values(e?.keyValue || {})); return uid;
} catch (e) {
if (e?.code === 11000) {
// Duplicate Key Error
throw new UserAlreadyExistError(Object.values(e?.keyValue || {}));
}
if (!autoAlloc || JSON.stringify(e.keyPattern) !== '{"_id":1}') throw e;
} }
throw e; uid++;
} }
return uid;
} }
@ArgMethod @ArgMethod