首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何解决这个TypeORM错误,“不推荐使用EntityRepository,而是使用Repository.extend函数”?

如何解决这个TypeORM错误,“不推荐使用EntityRepository,而是使用Repository.extend函数”?
EN

Stack Overflow用户
提问于 2022-03-21 12:01:18
回答 8查看 22.8K关注 0票数 16

但是,我在Repository类中找不到任何Repository.extend方法,而且文档中也没有关于它的任何内容。如何解决这个问题?

打字机版本:"^0.3.0“

我正在使用nest并尝试创建一个自定义存储库。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2022-04-17 16:18:06

首先:

代码语言:javascript
运行
复制
npm install @nestjs/typeorm@next

注意事项

在我的项目中,@nestjs/typeorm版本是9.0.0-next.2类型是,版本是0.3.6

在项目的src中创建一个名为数据库的文件夹,然后在(typeorm-ex.decorator.tstypeorm-ex.module.ts)中创建两个文件

代码语言:javascript
运行
复制
// typeorm-ex.decorator.ts

import { SetMetadata } from "@nestjs/common";

export const TYPEORM_EX_CUSTOM_REPOSITORY = "TYPEORM_EX_CUSTOM_REPOSITORY";

export function CustomRepository(entity: Function): ClassDecorator {
  return SetMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, entity);
}

和下一个文件

代码语言:javascript
运行
复制
// typeorm-ex.module.ts

import { DynamicModule, Provider } from "@nestjs/common";
import { getDataSourceToken } from "@nestjs/typeorm";
import { DataSource } from "typeorm";
import { TYPEORM_EX_CUSTOM_REPOSITORY } from "./typeorm-ex.decorator";

export class TypeOrmExModule {
  public static forCustomRepository<T extends new (...args: any[]) => any>(repositories: T[]): DynamicModule {
    const providers: Provider[] = [];

    for (const repository of repositories) {
      const entity = Reflect.getMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, repository);

      if (!entity) {
        continue;
      }

      providers.push({
        inject: [getDataSourceToken()],
        provide: repository,
        useFactory: (dataSource: DataSource): typeof repository => {
          const baseRepository = dataSource.getRepository<any>(entity);
          return new repository(baseRepository.target, baseRepository.manager, baseRepository.queryRunner);
        },
      });
    }

    return {
      exports: providers,
      module: TypeOrmExModule,
      providers,
    };
  }
}

打开AppModule并修改它,如下所示:

代码语言:javascript
运行
复制
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mssql',
      ...
      entities: [Photo],
    }),
    TypeOrmExModule.forCustomRepository([PhotoRepository]),
    ...
  ],
  controllers: [AppController],
  providers: [
    AppService
  ],
})
export class AppModule { }

您可以创建客户存储库,如下所示:

代码语言:javascript
运行
复制
@CustomRepository(Photo)
export class PhotoRepository extends Repository<Photo> {
    public async getAllPhoto() {
        const query = this.createQueryBuilder('photo')
            .where('photo.isPublished = :isPublished', { isPublished: true })
        const photos = await query.getMany()
        return photos
    }
}

一切都很完美。

多亏了 @anchan828

票数 13
EN

Stack Overflow用户

发布于 2022-06-22 19:59:22

在新版本的TypeORM (0.3.*)中,我正在将自定义存储库更改为服务。基于与多个正式文件数据库的连接。https://docs.nestjs.com/techniques/database#multiple-databases

自定义存储库

代码语言:javascript
运行
复制
  @EntityRepository(Person)
  export class PersonRepository extends Repository<Person> {...}

自定义存储库即服务

代码语言:javascript
运行
复制
  @Injectable()
  export class PersonRepository {
    constructor(private dataSource: DataSource) { }

    exampleQueryBuilder() {
      return this.dataSource
          .getRepository(Person)
          .createQueryBuilder() ...
    }

存储库注入

代码语言:javascript
运行
复制
  @Injectable()
  export class PersonService {
    constructor(
      @Inject(PersonRepository)
      private readonly personRepository: PersonRepository,
    ) {}
票数 4
EN

Stack Overflow用户

发布于 2022-06-28 06:13:27

解决此错误的方法如下:

首先,我创建了文件datasource.ts,我还声明了数据源,它的结构与ormconfig.js文件相同:

代码语言:javascript
运行
复制
import { DataSource } from 'typeorm';
require('dotenv').config();

export const AppDataSource = new DataSource({
  type: 'mongodb',
  url: process.env.MONGO_URI,
  useNewUrlParser: true,
  synchronize: true,
  logging: true,
  database: process.env.DB_DATABASE,
  entities: ['dist/entities/*.js'],
  useUnifiedTopology: true,
});

AppDataSource.initialize()
  .then(() => {
    console.log('Data Source has been initialized!');
  })
  .catch((err) => {
    console.error('Error during Data Source initialization', err);
  });

之后,我创建了一个自定义存储库:

代码语言:javascript
运行
复制
import { AppDataSource } from '@CustomDataSource';
import { Product } from '@Entities';
import { CreateProductDto, UpdateProductDto } from '@Products';

const dataSource = AppDataSource;
export const ProductRepository = 
dataSource.getMongoRepository(Product).extend({
async findOneById(id: number): Promise<Product> {
    const product = await ProductRepository.findOne({ where: { id }});
    return product;
  },
async findMany(): Promise<Product[]> {
    const products = await ProductRepository.find();
    return products;
  },
});

这样,您就不必在TypeORMModule.forFeature([])中为您工作的每个模块添加存储库。注意,现在我们不调用this,而是直接调用ProductRepository和方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71557301

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档