gpt4 book ai didi

repository - NestJS y TypeORM : InjectRepository undefined

转载 作者:行者123 更新时间:2023-12-05 02:10:13 27 4
gpt4 key购买 nike

我在使用 nestjs 和 TypeORM 开发的服务中遇到问题

系统使用 docker 运行,在我的电脑上一切正常,但当我在任何其他端运行时它停止工作。

错误说:

TypeError: Cannot read property 'findOne' of undefined

基本资料库:

export abstract class BasicRepository<Entity> {

constructor(protected readonly repository: Repository<Entity>,
protected readonly request: Request) {
console.log("basicRepo", this.repository.metadata.givenTableName)
}
}

用户资料库:

import { Inject, Injectable, Scope } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { BasicRepository } from './basic.repository';
import { UserEntity } from '../../shared/entities/user.entity';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

@Injectable({ scope: Scope.REQUEST })
export class UserRepository extends BasicRepository<UserEntity> {

constructor(
@InjectRepository(UserEntity) public readonly repository: Repository<UserEntity>,
@Inject(REQUEST) public readonly request: Request,
) {
super(repository, request);
}
}

点击存储库:

import { Inject, Injectable, Scope } from '@nestjs/common';
import { Repository, FindManyOptions, getConnection, getManager } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { BasicRepository } from './basic.repository';
import { TapEntity} from '../../shared/entities/tap.entity';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

@Injectable({ scope: Scope.REQUEST })
export class TapRepository extends BasicRepository<TapEntity> {

constructor(
@InjectRepository(TapEntity) public readonly repository: Repository<TapEntity>,
@Inject(REQUEST) public readonly request: Request,
) {
super(repository, request);
}
}

奇怪的是,在这种情况下,UserRepository 并没有给我错误,而是其他错误。

该系统只能在我的电脑上运行,我通常使用 kubernetes 运行该系统,当我想在 GKE(谷歌)或 EKS(亚马逊)上运行时它会失败。

发生的另一件事是打印存储库表名称的“basicRepo”消息仅使用 UserRepository 类打印。

最佳答案

解决方案很简单,而不是使用 @InjectRepository() 使用 typeorm 中的这个 Connection 来获取这样的存储库并初始化。

export class UserService {
private userRepository: UserRepository;
private authRepository: AuthRepository;
constructor(
private readonly connection: Connection
) {
this.userRepository = this.connection.getCustomRepository(UserRepository);
this.authRepository = this.connection.getCustomRepository(AuthRepository);
}
}

现在它像魅力一样工作:)

关于repository - NestJS y TypeORM : InjectRepository undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58995838/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com