【问题标题】:How to create custom (separate file) repository in NestJS 9 with TypeORM 0.3.x如何使用 TypeORM 0.3.x 在 NestJS 9 中创建自定义(单独的文件)存储库
【发布时间】:2022-11-23 19:46:00
【问题描述】:

这不是重复的问题。请不要将其标记为那个。

以下不是我想要的

import { EntityRepository, Repository } from "typeorm";
import { Test } from "./test.model";
import { Injectable } from "@nestjs/common";

@EntityRepository(Test)
export class TestRepository extends Repository<Test> {}

@EntityRepository 装饰器现已弃用。

我也不想在这里制作一个假的存储库: https://stackoverflow.com/a/73352265/5420070

也不想要这个,因为我必须从 dataSource 中提取 manager,我不想要这个,因为我认为这不是最好的方法。

    export const UserRepository = dataSource.getRepository(User).extend({
        //                        ^^^^^^^^^^ from where this came from
        findByName(firstName: string, lastName: string) {
            return this.createQueryBuilder("user")
                .where("user.firstName = :firstName", { firstName })
                .andWhere("user.lastName = :lastName", { lastName })
                .getMany()
        },
    })

在上面找到:https://orkhan.gitbook.io/typeorm/docs/custom-repository#how-to-create-custom-repository

我不认为这是在 NestJS 上下文中。

我想要的是 想知道在最新版本的 NestJS (v9) 和 TypeORM (v0.3) 中创建自定义存储库的正确方法。在 @EntityRepository deprecation note 中,他们说需要扩展 repo 来创建像 someRepo.extend({}) 这样的自定义 repo。我想知道如何以 NestJS 的方式做到这一点

【问题讨论】:

    标签: nestjs typeorm repository-pattern


    【解决方案1】:
    import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from "typeorm";
    import { CustomBaseEntity } from "../core/custom-base.entity";//custom-made
    @Entity({name: 'rcon_log', schema: 'dbo'})
    export class LogEntity extends CustomBaseEntity{
    ------------your code-----------
    }
    

    【讨论】:

      【解决方案2】:

      为了实现您想要的,您可以执行以下操作。

      这个方案是受官方NestJS docs related to this topic的启发,做了一些定制。

      实现步骤:

      1. 创建你的TypeOrm像往常一样实体,比方说UserEntity用户.entity.ts文件)
      2. 创建一个UserRepository类(用户.repository.ts文件)
      3. 照常创建一个UserService类(用户服务.ts文件)
      4. UserRepository导入你的UserService
      5. 更新UserModule以提供UserRepository和需要的UserEntity

        详细实现示例

        1.用户.entity.ts文件

        import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
        
        @Entity()
        export class UserEntity {
          @PrimaryGeneratedColumn()
          id: number;
        
          @Column()
          firstName: string;
        
          @Column()
          lastName: string;
        
          @Column({ default: true })
          isActive: boolean;
        }
        

        2.用户.repository.ts文件

        import { InjectRepository } from '@nestjs/typeorm';
        import { Repository } from 'typeorm';
        import { UserEntity } from './user.entity';
        
        export class UserRepository extends Repository<UserEntity> {
            constructor(
                @InjectRepository(UserEntity)
                private userRepository: Repository<UserEntity>
            ) {
                super(userRepository.target, userRepository.manager, userRepository.queryRunner);
            }
        
            // sample method for demo purposes
            async findByEmail(email: string): Promise<UserEntity> {
                return await this.userRepository.findOneBy({ email }); // could also be this.findOneBy({ email });, but depending on your IDE/TS settings, could warn that userRepository is not used though. Up to you to use either of the 2 methods
            }
            
            // your other custom methods in your repo...
        }
        

        3. & 4.用户服务.ts文件

        import { Injectable } from '@nestjs/common';
        import { InjectRepository } from '@nestjs/typeorm';
        import { UserRepository } from './user.repository';
        import { UserEntity } from './user.entity';
        
        @Injectable()
        export class UserService {
          constructor(
            private readonly userRepository: UserRepository, // import as usual
          ) {}
        
          findAll(): Promise<UserEntity[]> {
            return this.userRepository.find();
          }
          
          // call your repo method
          findOneByEmail(email: string): Promise<UserEntity> {
            return this.userRepository.findByEmail({ email });
          }
        
          findOne(id: number): Promise<UserEntity> {
            return this.userRepository.findOneBy({ id });
          }
        
          async remove(id: string): Promise<void> {
            await this.userRepository.delete(id);
          }
          
          // your other custom methods in your service...
        }
        

        5.更新UserModule(用户.module.ts文件)

        import { Module } from '@nestjs/common';
        import { TypeOrmModule } from '@nestjs/typeorm';
        import { UserService } from './user.service';
        import { UserController } from './user.controller';
        import { UserEntity } from './user.entity';
        
        @Module({
          imports: [TypeOrmModule.forFeature([UserEntity])], // here we provide the TypeOrm support as usual, specifically for our UserEntity in this case
          providers: [UserService, UserRepository], // here we provide our custom repo
          controllers: [UserController],
          exports: [UserService, UserRepository] // add this only if you use service and/or custom repo within another module/service
        })
        export class UserModule {}
        

        有了这个,您应该能够在您的AppModule 中导入UserModule,并且能够在UserRepository 中实现自定义方法并在UserService 中使用它们。您还应该能够调用自定义存储库的 managerqueryRunnner

        附加说明

        如果您需要从另一个模块/服务中直接调用您的 UserRepository 方法,请更新 UserModule 以导出 UserRepository

        希望对您有所帮助,不要犹豫,发表评论。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-05
        • 2021-06-08
        • 2022-07-07
        • 2022-12-04
        • 2021-06-07
        • 2020-07-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多