Skip to content
This repository was archived by the owner on Nov 16, 2023. It is now read-only.
This repository was archived by the owner on Nov 16, 2023. It is now read-only.

User.ts - why Pre Middleware instead of setter for password? #344

@gaborszita

Description

@gaborszita

In the src/models/User.ts file, to hash the password using bcrypt, the program is using a Pre Middleware instead of a setter for the password:

/**
 * Password hash middleware.
 */
userSchema.pre("save", function save(next) {
    const user = this as UserDocument;
    if (!user.isModified("password")) { return next(); }
    bcrypt.genSalt(10, (err, salt) => {
        if (err) { return next(err); }
        bcrypt.hash(user.password, salt, undefined, (err: mongoose.Error, hash) => {
            if (err) { return next(err); }
            user.password = hash;
            next();
        });
    });
});

Just wondering, why is it using a middleware instead of a simple setter? I think this was done this way so that it could use asynchronous bcrypt functions, but correct me if I'm wrong. If this is the reason, this was a really good design choice.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions