-
-
Save Asraf2asif/45b07cb0424414e5220098803416fa4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SALT_WORK_FACTOR = 10; | |
UserSchema.pre('insertMany', async (next, users) => { | |
if (Array.isArray(users) && users.length > 0) { | |
const hashedUsers = users.map(async (user) => { | |
return await new Promise((resolve, reject) => { | |
bcrypt | |
.genSalt(SALT_WORK_FACTOR) | |
.then((salt) => { | |
bcrypt | |
.hash(user.password.toString(), salt) | |
.then((hash) => { | |
user.password = hash; | |
resolve(user); | |
}) | |
.catch((hashError) => { | |
reject(hashError); | |
}); | |
}) | |
.catch((saltError) => { | |
reject(saltError); | |
}); | |
}); | |
}); | |
users = await Promise.all(hashedUsers); | |
next(); | |
} else { | |
return next(new Error('User list should not be empty')); // lookup early return pattern | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UserSchema.pre('save', function (next) { | |
let user = this | |
if (!user.isModified("password")) { | |
next() | |
} else { | |
bcrypt.genSalt(10, function (err, salt) { | |
if (err) return next(err) | |
bcrypt.hash(user.password, salt, function (err, hash) { | |
if (err) return next(err) | |
user.password = hash | |
next() | |
}) | |
}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment