mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-20 01:38:19 +08:00
core: user_create: add optimistic loop
This commit is contained in:
1 file changed
+9
-3
@@ -312,12 +312,16 @@ 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;
|
||||||
}
|
}
|
||||||
|
const salt = String.random();
|
||||||
|
while (true) { // eslint-disable-line no-constant-condition
|
||||||
try {
|
try {
|
||||||
|
// eslint-disable-next-line no-await-in-loop
|
||||||
await coll.insertOne({
|
await coll.insertOne({
|
||||||
_id: uid,
|
_id: uid,
|
||||||
mail,
|
mail,
|
||||||
@@ -334,14 +338,16 @@ class UserModel {
|
|||||||
priv,
|
priv,
|
||||||
avatar: `gravatar:${mail}`,
|
avatar: `gravatar:${mail}`,
|
||||||
});
|
});
|
||||||
|
return uid;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e?.code === 11000) {
|
if (e?.code === 11000) {
|
||||||
// Duplicate Key Error
|
// Duplicate Key Error
|
||||||
throw new UserAlreadyExistError(Object.values(e?.keyValue || {}));
|
throw new UserAlreadyExistError(Object.values(e?.keyValue || {}));
|
||||||
}
|
}
|
||||||
throw e;
|
if (!autoAlloc || JSON.stringify(e.keyPattern) !== '{"_id":1}') throw e;
|
||||||
|
}
|
||||||
|
uid++;
|
||||||
}
|
}
|
||||||
return uid;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ArgMethod
|
@ArgMethod
|
||||||
|
|||||||
Reference in new issue
Block a user