typeorm-typedi-extensions icon indicating copy to clipboard operation
typeorm-typedi-extensions copied to clipboard

Allow @InjectRepository with a function

Open maksimkurb opened this issue 6 years ago • 8 comments

I have some circular depended entities (User and Token) and when I injecting Repository<User> and Repository<Token> in some class, User is undefined on the moment of the class construction.

class SomeController {
  @InjectRepository(Token)
  private tokenRepo: Repository<Token>

  @InjectRepository(User) // User is undefined, so error is occured
  private userRepo: Repository<User>
}

Error message: Missing "entityType" parameter of "@InjectRepository" decorator for a ...

If you allow to provide functions that returns class type, it will solve this problem:

  @InjectRepository(of => Token) // like in TypeDI: @Inject(type => SomeService)
  private tokenRepo: Repository<Token>

  @InjectRepository(of => User)
  private userRepo: Repository<User>

maksimkurb avatar Mar 19 '19 15:03 maksimkurb

I would greatly appreciate this functionality as well!

smithki avatar May 08 '19 22:05 smithki

are there any workarounds for solving the circular dependency issue?

afiorito avatar Jun 03 '19 16:06 afiorito

Any updates on this issue?

glentakahashi avatar Nov 13 '19 00:11 glentakahashi

I ran into this as well. To resolve, I patched the inject repository by checking if the metadata exists by calling connection.hasMetadata for the entity type. If not, I assume the entity is a function returning the entity type and I use the return value as entity type. It was a bit tricky to figure out if the func is an entity or a function returning an entity. Is there a better way to do this?

I don't know if I should spent time creating a pull request as #37 is also still open.

martijndeh avatar Jan 09 '20 15:01 martijndeh

Is this something you can advise on @MichalLytek as you've approved #37?

martijndeh avatar Jan 16 '20 10:01 martijndeh

I have some circular depended entities (User and Token) and when I injecting Repository<User> and Repository<Token> in some class, User is undefined on the moment of the class construction.

Do you have every entity and controller in different files?

MichalLytek avatar Jan 16 '20 10:01 MichalLytek

are there any workarounds for solving the circular dependency issue?

@afiorito This article may help - https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de

udayrajMT avatar Aug 22 '20 15:08 udayrajMT

Not to pollute the comments, but +1 to the article that @udayrajMT linked. We have been using the internal.ts pattern with typeorm + type-graphql for months in production without any issue and we haven't run into a single circular dependency issue since.

glentakahashi avatar Aug 22 '20 20:08 glentakahashi