Skn0tt / nextjs-nestjs-integration-example

https://nextjs-nestjs-integration-example.now.sh
156 stars 36 forks source link

Issue with `InjectRepository` calls #20

Closed szabolcs-szilagyi closed 3 years ago

szabolcs-szilagyi commented 3 years ago

I could not figure out sofar what is wrong, but when would like use multiple repositories in a single service one of them turns up undefined.

Eg.: token.service.ts

@Injectable()
export class TokenService {
  constructor(
    @InjectRepository(LoginTokenRepository)
    private readonly loginTokenRepository: LoginTokenRepository,
    @InjectRepository(SessionTokenRepository)
    private readonly sessionTokenRepository: SessionTokenRepository,
  ) {}

  // ....
}

login-token.repository.ts

import { EntityRepository, Repository } from "typeorm";
import { LoginToken } from "./entities/login-token.entity";

@EntityRepository(LoginToken)
export class LoginTokenRepository extends Repository<LoginToken> {}

the SessionTokenRepository is the same as the login-token one, just different name, table and columns on the db. Don't ask why the two similar token stuff, in the process to rewriting some PHP project with existing db and front-end.

Error:

ReferenceError: LoginTokenRepository is not defined
    at eval (webpack-internal:///./src/backend/token/token.service.ts:59:93)

if I swap the two parameters in the constructor of the service, then it will complain about the other repository not being defined.

Also created a small example to test with TypeORM and MongoDB: https://github.com/Skn0tt/nextjs-nestjs-integration-example/compare/master...szabolcs-szilagyi:test-multi-repository

Skn0tt commented 3 years ago

My first suspicion was that this is a problem with NestJS and not with the integration pattern that's presented in this repository. But, indeed - it is! When running via Nest's own listen, and not via Next, it works as intended.

Interestingly, yarn build yields ReferenceError: InjectRepository is not defined. I suspect a bug in @babel/plugin-proposal-decorators or babel-plugin-parameter-decorator. These are the Babel plugins used to transpile decorators.

Skn0tt commented 3 years ago

Got it! From babel-plugin-parameter-decorator:

By default, @babel/preset-typescript will remove imports only referenced in Decorators. Since this is prone to break Decorators, make sure disable it by setting onlyRemoveTypeImports to true.

This is exactly what happens here. LoginTokenRepository / InjectRepository are elided from the bundle, that's why they're "not defined".

I updated this repository's Babel config to implement the suggested fix.

szabolcs-szilagyi commented 3 years ago

I've read that multiples times, but didn't connect the dots, plus the next/babel options :sweat_smile: Thanks for the help @Skn0tt!