Pre hooks
Pre hooks
Example
const { instances } = require('gstore-node');
const bscrypt = require('bcrypt-nodejs');
const gstore = instances.get('default');
const userSchema = new gstore.Schema({
user: { type: String },
email: { type: String, validate: 'isEmail' },
password: { type: String, excludeFromIndexes: true }
});
// Hash password middleware
function hashPassword() {
// scope *this* is the entity instance
const _this = this;
const password = this.password;
if (!password) {
// nothing to hash... exit
return Promise.resolve();
}
return new Promise((resolve, reject) => {
bcrypt.genSalt(5, function onSalt(err, salt) {
if (err) {
return reject(err);
};
bcrypt.hash(password, salt, null, function onHash(err, hash) {
if (err) {
// reject will *not* save the entity
return reject(err);
};
_this.password = hash;
// resolve to go to next middleware or target method
return resolve();
});
});
});
}
// add the "pre" middleware to the save method
userSchema.pre('save', hashPassword);
...
// Then when you create a new user and save it (or when updating it)
// the password will automatically be hashed
const User = require('./user.model');
const user = new User({ username: 'john', password: 'mypassword' });
user.save()
.then((response) => {
const entity = response[0];
console.log(entity.password);
// $7b$01$GE/7OqVnMyThnaGC3QfEwuQ1imjifli3MvjcP7UGFHAe2AuGzne5.
});Dataloader instance
Override parameters
Last updated
Was this helpful?