【问题标题】:Sequelize Typescript @BeforeUpdate Hook not workingSequelize Typescript @BeforeUpdate Hook 不起作用
【发布时间】:2020-03-24 19:58:31
【问题描述】:

我正在为我的无服务器 lambda 函数使用 Sequelize Typescript 模块。用户模型有两个钩子,beforecreate 和 beforeupdate。用户模型如下所示:

import { Table, Column, ForeignKey, BeforeCreate, BeforeUpdate, BelongsTo } from 'sequelize-typescript';
import { Role } from './role';
import bcrypt from 'bcrypt-nodejs';
import { BaseModel } from './base';
const saltRounds = 10;

@Table({
    tableName: 'users'
})

export class User extends BaseModel {

    @Column
    firstName!: string;

    @Column
    lastName!: string;

    @Column
    password!: string;

    @Column
    email!: string;

    @Column
    isActive!: boolean;

    @Column
    companyId: string

    @ForeignKey(() => Role)
    @Column
    roleId!: string;

    @BelongsTo(() => Role)
    role!: Role;

    @BeforeCreate
    @BeforeUpdate
    static hashPassword(user: User) {
        if (user.password) {            
            var salt = bcrypt.genSaltSync(saltRounds);
            user.password = bcrypt.hashSync(user.password, salt);
        }
    }
}

现在,当我创建一个新用户时,模型会对密码进行哈希处理并将哈希密码保存在表中,但是当我尝试更新用户的密码时,密码会以纯文本形式保存。所以我猜@BeforeCreate 有效,而@BeforeUpdate 钩子没有。

我什至尝试将两个钩子分开并赋予它们自己的功能:

@BeforeCreate
static hashPasswordBeforeCreate(user: User) {
    if (user.password) {            
        var salt = bcrypt.genSaltSync(saltRounds);
        user.password = bcrypt.hashSync(user.password, salt);
    }
}


@BeforeUpdate
static hashPasswordBeforeUpdate(user: User) {
    if (user.password) {            
        var salt = bcrypt.genSaltSync(saltRounds);
        user.password = bcrypt.hashSync(user.password, salt);
    }
}

但是之前的更新还是不行。我做错了什么?

【问题讨论】:

    标签: sequelize.js sequelize-typescript


    【解决方案1】:

    我认为你必须添加

    individualHooks: true

    在这样的更新查询中 - users.update(data, {where: {id}, individualHooks: true});

    然后,您可以像 user.dataValues 一样将数据访问到 @BeforeUpdate 挂钩中。

    例如

    @BeforeUpdate
    static hashPasswordBeforeUpdate(user: User) {
            user.dataValues.password = bcrypt.hashSync(user.dataValues.password, salt);
    }
    

    这个方法对我来说很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多