Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection "default" was not found - TypeORM, NestJS and external NPM Package

Tags:

typeorm

nestjs

I'm using NestJs to create a couple of applications and I want to move the code from a NestInterceptor for an external NPM Package so I can use the same interceptor in multiple applications.

The problem is that the same code that works when used "locally" just stop working when moved to the external package.

Here's the code for the interceptor:

import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '@nestjs/common'
import { map } from 'rxjs/operators'
import { getManager } from 'typeorm'
import jwt_decode from 'jwt-decode'

@Injectable()
export class MyInterceptor implements NestInterceptor {
  entity: any

  constructor(entity: any) {
    this.entity = entity
  }

  async intercept(context: ExecutionContext, next: CallHandler): Promise<any> {

    const request = context.switchToHttp().getRequest()

    const repository = getManager().getRepository(this.entity)

    return next.handle().pipe(map((data) => data))
  }
}

Here's a given controller:

import { myInterceptor } from "../src/interceptors/interceptor.ts";

@UseInterceptors(new CompanyIdInterceptor(User))
export class UserController {
}

This works fine, but if a move the file to an external NPM package and import from it like this:

import { myInterceptor } from "mynpmpackage";

I get the following error:

[Nest] 24065   - 04/18/2019, 10:04 AM   [ExceptionsHandler] Connection "default" was not found. +26114ms
ConnectionNotFoundError: Connection "default" was not found.
    at new ConnectionNotFoundError (/home/andre/Services/npm-sdk/src/error/ConnectionNotFoundError.ts:8:9)
    at ConnectionManager.get (/home/andre/Services/npm-sdk/src/connection/ConnectionManager.ts:40:19)

Any ideas, on what causes this and how to solve it?

like image 808
André Oliveira Avatar asked Apr 18 '19 13:04

André Oliveira


1 Answers

This might not be your problem exactly, but I had a similar problem when moving things to external packages with TypeORM. Make sure all packages from parent project are using the same version of the TypeORM package.

In my case, using yarn why typeorm showed me two different versions were being installed. One of them was used to register the entities, while the framework connected to the SQL database using another version, generating this clash.

Check your versions using yarn why [pkg-name] or if you're using NPM, try npx npm-why [pkg-name] or install globally from https://www.npmjs.com/package/npm-why.

like image 158
Luís Brito Avatar answered Sep 23 '22 11:09

Luís Brito