三行代码  ›  专栏  ›  技术社区  ›  Brotzka

带有TypeORM的NesteJS-钩子和侦听器不工作

  •  0
  • Brotzka  · 技术社区  · 1 周前

    解决方案

    create 作用 player.service.ts

    async create(createPlayerDto: CreatePlayerDto): Promise<Player> {
      const newPlayer = this.playerRepository.create(createPlayerDto);
      return await this.playerRepository.save(newPlayer);
    }
    

    我的球手的钩子。实体ts:

    @BeforeInsert()
    async hashPassword() {
      console.log('Hash password!');
      this.password = await bcrypt.hash(this.password, this.saltOrRounds);
    }
    

    问题

    对于使用NestJS的项目,我创建了一个播放器实体( player.entity.ts ),它具有以下列和一个挂钩。我已经连接了一个MySQL8。通过TypeORM包访问0数据库。

    import {
      Entity,
      Column,
      PrimaryGeneratedColumn,
      CreateDateColumn,
      UpdateDateColumn,
      BeforeInsert,
    } from 'typeorm';
    
    import * as bcrypt from 'bcrypt';
    
    @Entity({ name: 'players' })
    export class Player {
      readonly saltOrRounds = 10;
    
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column({
        type: 'varchar',
        unique: true,
      })
      username: string;
    
      @Column()
      password: string;
    
      @Column({
        unique: true,
        type: 'varchar',
      })
      email: string;
    
      @CreateDateColumn({
        name: 'created_at',
        type: 'datetime',
      })
      created_at: 'datetime';
    
      @UpdateDateColumn({
        name: 'updated_at',
        type: 'datetime',
      })
      updated_at: 'datetime';
    
      @BeforeInsert()
      async hashPassword() {
        return (
          this.password && (await bcrypt.hash(this.password, this.saltOrRounds))
        );
      }
    }
    

    正如你所看到的 @BeforeInsert() hook应该获取密码,对其进行散列,然后返回散列后的密码。

    创建新玩家的相关路径位于 players.controller.ts :

    import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
    import { PlayersService } from './players.service';
    import { CreatePlayerDto } from './dto/create-player.dto';
    import { Player } from './interfaces/player.interface';
    
    @Controller('players')
    export class PlayersController {
      constructor(private playerService: PlayersService) {}
    
      @Post()
      async create(@Body() createPlayerDto: CreatePlayerDto) {
        return this.playerService.create(createPlayerDto);
      }
    }
    

    游戏者服务ts 并使用EntityManager执行创建/插入操作:

    import { Injectable } from '@nestjs/common';
    import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
    import { Player } from './entities/player.entity';
    import { EntityManager, Repository } from 'typeorm';
    import { CreatePlayerDto } from './dto/create-player.dto';
    
    @Injectable()
    export class PlayersService {
      constructor(
        @InjectEntityManager()
        private entityManager: EntityManager,
        @InjectRepository(Player)
        private playerRepository: Repository<Player>,
      ) {}
    
      async create(createPlayerDto: CreatePlayerDto): Promise<Player> {
        return this.entityManager.save(Player, createPlayerDto);
      }
    }
    

    /create 终点。但不幸的是,使用的钩子和/或侦听器都不起作用。

    1 回复  |  直到 1 周前
        1
  •  1
  •   sid    1 周前

    实例化实体,为其分配属性,然后保存。

    async create(attributes: DeepPartial<T>) {
        const playerEntity = Object.assign(new Player(), attributes);
        return this.repository.save(playerEntity);
    }
    

    或者你可以使用 create 然后将其保存到存储库中。

    const record = playerRepository.create(attributes);
    await playerRepository.save(record);