BeforeInsert 和 AfterInsert 钩子未被调用

W. *_*yna 1 sqlite graphql typeorm nestjs

我有一个BeforeInsertandAfterInsert钩子没有被调用。它所做的只是记录hook。我正在使用 Nestjs-graphql。

您可以运行此示例npm i,然后发送一个突变(playground 位于localhost:3000/graphql)body 处createUser(createInput:{password:"password" email:"test@test.com"})。它应该成功并记录hook

钩子(没有记录任何内容):

@Entity('user')
export default class UserEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    @IsEmail()
    email: string;

    @Column()
    @Length(7, 42)
    password: string;

    @BeforeInsert()
    @AfterInsert()
    async validate() {
        console.log("hook")
    }
}
Run Code Online (Sandbox Code Playgroud)

它是从服务中调用的。插入不会引发错误,并here2会被记录:

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(UserEntity)
        private readonly userRepository: Repository<UserEntity>,
    ) { }

    async createNew(email: string, password: string): Promise<number> {
        console.log("here2")
        const hashedPassword = "test"
        const res = await this.userRepository.insert({ email, password: hashedPassword })
        return res.identifiers[0].id
    }
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 5

根据TypeORM 的文档,当使用实体管理器或存储库的save方法时,侦听器挂钩会在各自的操作之前或之后被调用。由于insert和类似的操作不调用save,它们不执行@Before/After*方法