How to adjust my code to comply with Google Javascript Style Guide section 5.9?

How to adjust my code to comply with Google Javascript Style Guide section 5.9?
0.0 0

#1

I have been updating an applications code to be 100% compliant with Google’s Javascript Style Guide and have come across an issue I’m unsure how to adjust my code to be complaint. More information is below, any help would be appreciated :slight_smile:

Mongoose.js User Schema password hashing code:
This pre-insert function ensures the user’s password is hashed with bcrypt. However due to it refering to itself (this) it fails to meet the “no-invalid-this” requirement.

  UserSchema.pre('save', (next) => {
    bcrypt.hash(this.password, 10, (err, hash) => {
      if (err) {
        return next(err);
      }
      this.password = hash;
      next();
    });
  });
  50:18  error  Unexpected 'this'  no-invalid-this

5.9 this
Only use this in class constructors and methods, or in arrow functions defined within class constructors and methods. Any other uses of this must have an explicit @this declared in the immediately-enclosing function’s JSDoc.

Never use this to refer to the global object, the context of an eval, the target of an event, or unnecessarily call()ed or apply()ed functions.

Source: https://google.github.io/styleguide/jsguide.html#features-this


#2

Does this work?

UserSchema.pre('save', (next) => {
    var mypassword = this.password;
    bcrypt.hash(mypassword, 10, (err, hash) => {
      if (err) {
        return next(err);
      }
      mypassword = hash;
      next();
    });
  });


#3

Section 5.1.1 of Google’s javascript style guide prohibits the usage of var however const and let are allowed. I did tryusing const instead but to no avail.


#4

Did you try let?
It’s not a constant, isn’t it?


#5

That did not work either. It considers the usage of this inside a function bad, I think you are only allowing to use “this” inside of an object. Is there an alternative to using this to still get the password for the pre-save method?