Connection "default" was not found - TypeORM, NestJS and external NPM Package - 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?

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.

After verifying TypeOrm versions is same in both the packages i.e- external package and consumer repository as mentioned by #Luís Brito still issue persist then issue could be-
Basically when we create an external package - TypeORM tries to get the "default" connection option, but If not found then throws an error:
ConnectionNotFoundError: Connection "default" was not found.
We can solve this issue by doing some kind of sanity check before establishing a connection - luckily we have .has() method on getConnectionManager().
import { Connection, getConnectionManager, getConnectionOptions,
createConnection, getConnection, QueryRunner } from 'typeorm';
async init() {
let connection: Connection;
let queryRunner: QueryRunner;
if (!getConnectionManager().has('default')) {
const connectionOptions = await getConnectionOptions();
connection = await createConnection(connectionOptions);
} else {
connection = getConnection();
}
queryRunner = connection.createQueryRunner();
}
Above is a quick code-snippet which was the actual root cause for this issue but If you are interested to see complete working repositories (different example) -
External NPM Package :
Git Repo : git-unit-of-work (specific file- src/providers/typeorm/typeorm-uow.ts)
Published in NPM : npm-unit-of-work
Consumer of above package : nest-typeorm-postgre (specific files- package.json, src/countries/countries.service.ts & countries.module.ts)

Related

Nest can't resolve dependencies of the XXX after upgrade from 8 to 9

Nestjs app stop working after upgrading from version 8 to 9
I recently upgraded my nestjs project from 8.x.x to 9.2.1
Since this moment my application stop working and I'm keep getting error: "Nest can't resolve dependencies of the XXX" in all of my resources.
Before I upgraded everything worked perfect.
[Nest] 410513 - 08/12/2022, 17:07:21 ERROR [ExceptionHandler] Nest can't resolve dependencies of the LoanService (PrismaService, ConfigService, StatusesHelper, LoanHelper, QuestionnaireHelper, EventEmitter, DATABASE_CONNECTION, ?). Please make sure that the argument Object at index [7] is available in the LoanModule context.
Here is my service DI constractor:
import { StatusesHelper } from 'src/helpers/statuses.service';
import { LoanHelper } from 'src/helpers/loan.service';
import { Db, ObjectId } from 'mongodb';
import { QuestionnaireHelper } from 'src/helpers/questionnaire.helper';
import { RunWeights } from 'src/deal/events/run-weights.event';
import { EventEmitter2 } from '#nestjs/event-emitter';
import { User } from '#prisma/client';
import { TwilioClient } from 'nestjs-twilio';
#Injectable()
export class LoanService {
constructor(
private prisma: PrismaService
, private config: ConfigService
, private statuses: StatusesHelper
, private readonly loanHelper: LoanHelper
, private questionnaireHelper: QuestionnaireHelper
, private readonly eventEmitter: EventEmitter2
, #Inject('DATABASE_CONNECTION') private db: Db
, private readonly twilio: TwilioClient
) { }
Can someone please help me figure it out?
thanks.
It happens most of the time due to either that module is not imported or there is a circular dependency.

Prisma Issue of managing instances of Prisma Client actively running

I'm new to Prisma and Nodejs
I accidentally created lots of instances of Prisma Client that keep displaying the warning of
warn(prisma-client) There are already 10 instances of Prisma Client actively running.
Even I tried to delete old files and create a new Prisma, it keep showing the same warning.
I was wondering is there any way to clear the duplicated instances that already actively running?
I found a lot of INFO only about to prevent the situation occur instead of clearing it.
Node js version. : v14.18.2
NPM version. : 6.14.15
prisma : 3.7.0
#prisma/client : 3.7.0
Thank you for your help.
So the problem is that you are probably creating a new PrismaClient() every time you need to use it. The ideal would be to instantiate it once and only use that instance. In the docs they recommend it in this way
If you are in a serverless env, you can try this code as well:
import { PrismaClient } from "#prisma/client";
declare global {
namespace NodeJS {
interface Global {
prisma: PrismaClient;
}
}
}
let prisma: PrismaClient;
if (!global.prisma) {
global.prisma = new PrismaClient({
log: ["info"],
});
}
prisma = global.prisma;
export default prisma;
the problem is that you are probably creating a new PrismaClient()
you can use singleTon pattern to solve it ,(I'm use typescript here !)
import { PrismaClient } from '#prisma/client'
export class Prisma {
public static Prisma :PrismaClient ;
static getPrisma (){
//verify if prisma instance not exist
if (this.Prisma===null || !this.Prisma)
//create new one
this.Prisma=new PrismaClient()
return this.Prisma
}
}

Nestjs common repo dependency in conflicts with Project repo dependency

I'm working with a home grown mono repo structure in with NestJS and legacy code. The NestJS parts of the monorepo depend on a common folder in the root that is imported into each Nest Project via "commonPackage":"file:../common" in the package.json file.
The issue I'm experiencing is that the common folders install of #nestjs/config is conflicting with the consuming project's install of the same package. I've been using a workaround to import the necessary code from commonPackage/node_modules/#nestjs/config however that is using the common folder's .env file instead of the consuming project's .env
I have no runtime dependencies in the common package, and I've set #nestjs/config as a peer dependency with a version flag of ^1 however, when attempting to import the consuming project's config
(i.e. import {ConfigService} from '#nestjs/config'; and not the above) service I get an error about an internal property not matching in the spec like below.
src/app.module.ts:16:26 - error TS2345: Argument of type '(config: ConfigService) => ConnectionOptions' is not assignable to parameter of type '(config: ConfigService<Record<string, unknown>>) => ConnectionOptions'.
Types of parameters 'config' and 'config' are incompatible.
Type 'ConfigService<Record<string, unknown>>' is not assignable to type 'ConfigService<Record<string, unknown>, false>'.
Types have separate declarations of a private property 'internalConfig'.
16 MysqlModule.register(sqlConfig),
~~~~~~~~~
[3:47:23 PM] Found 1 error. Watching for file changes.
The workaround solution I worked out was to simply export the config service I was using for my internal module, however I now think it should be possible to pass in the config service when registering the module.
so My current solution is to export the config service from the module that uses it in the common repo:
export declare type SpecConfig = ConfigService;
Use this when defining factories that get put into that module.
*** One caveat is that you will not be able to specify a custom config file with this method as the import is handled in your register logic.***
another option is to add the config service as a dependency to the module registration, but I have yet to work that out.
for example this is my Dynamic Module that was causing the issue.
import { DynamicModule, Module, Provider } from '#nestjs/common';
import { ConfigModule, ConfigService } from '#nestjs/config';
import * as mysql from 'mysql2';
import { MysqlConnectionService } from './mysql-connection/mysql-connection.service';
#Module({})
export class MysqlModule {
static register(...options: MysqlModuleOptions[]): DynamicModule {
const providers: Provider<any>[] = options.map(({config: connectionConfig, name}) => {
const config = {
provide: `${name}-mysql-config`,
useFactory: connectionConfig,
inject: [ConfigService]
}
const provider = {
provide: `${name}-mysql`,
useFactory: (config: mysql.ConnectionOptions) => new MysqlConnectionService(config),
inject: [`${name}-mysql-config`],
}
return [config, provider];
}).reduce((acc, val) => acc.concat(val), [])
return {
module: MysqlModule,
imports: [ConfigModule.forRoot({isGlobal: true})],
providers: [...providers],
exports: [...providers]
}
}
}
export type MysqlConfigFunc = (config: ConfigService) => mysql.ConnectionOptions
export type MsqlConfigService = ConfigService;
export class MysqlModuleOptions {
name: string;
config: MysqlConfigFunc;
}

Domino 10 AppDevPack local installation problem

I am at this the third day now, but can't find the way to successfully use the AppDevPack on my local angular app. I am working on a Mac, I have Angular v 8.15.0. I was able to successfully install the library but when ever I wan't to compile it, it breaks.
To describe: I've done almost everything to the script. The only difference is that I have made a service in which the #domino lives(it is not directly on a component).
The main problem seems to be with grpc and then with stream.
import { Injectable } from '#angular/core';
//import { useServer } from '#domino/domino-db/';
import * as useServer from '../../../node_modules/#domino/domino-db';
#Injectable({
providedIn: 'root'
})
export class DominoService {
private serverConfig = {
hostName: 'http://www.hostname.com/',
connection: { port:'3002'}
};
private databaseConfig = {
filePath: 'dev-tmp.nsf'
};
public database: any;
constructor() {
useServer( this.serverConfig ).then( async server => {
this.database = await server.useDatabase( this.databaseConfig );
});
const coll = this.database.bulkReadDocuments({
query: "Form = 'Document'"
});
console.log("Returned docs:" + JSON.stringify(coll));
}
Here are some of the errors:
Critical dependency: the request of a dependency is an expression
WARNING in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/node-pre-gyp/lib/pre-binding.js
20:22-48 Critical dependency: the request of a dependency is an
expression
WARNING in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/node-pre-gyp/lib/util/versioning.js 17:20-67 Critical dependency: the request of a dependency is an
expression
WARNING in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/minimatch/minimatch.js
Module not found: Error: Can't resolve 'path' in
'/Users/…/node_modules/#domino/domino-db/node_modules/grpc/node_modules/minimatch'
ERROR in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib/detect-libc.js
Module not found: Error: Can't resolve 'child_process' in
‘/…/node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib'
Error: Can't resolve 'path' in
'/Users/.../node_modules/#domino/domino-db/node_modules/grpc/node_modules/minimatch'
ERROR in
./node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib/detect-libc.js
Module not found: Error: Can't resolve 'child_process' in
'/Users/.../node_modules/#domino/domino-db/node_modules/grpc/node_modules/detect-libc/lib'
ERROR in
./node_modules/#domino/domino-db/node_modules/grpc/src/client.js
Module not found: Error: Can't resolve 'stream' in
'/Users/.../node_modules/#domino/domino-db/node_modules/grpc/src'
Critical dependency: the request of a dependency is an expression
From the error message, I can see that you're trying to webpack this. We do not support running domino-db on a webpage. Even if you got past this error, domino-db would fail to load in that environment because it's insecure.
Domino-db in production, secure environments requires client credentials to log in. Those aren't things you want to appear in the browser page.

graphql-tag/index has no exported member 'gql'

I'm converting my Angular app REST backend to GraphQL. I'm trying to import gql from graphql-tag. I'm searching and searching and my import looks like everyone elses...
import { Angular2Apollo } from 'angular2-apollo';
import { ApolloClient } from 'apollo-client';
import { gql } from 'graphql-tag';
But the gql has the red underline indicating not found. When i run ng serve I get this error in cmder...
... /node_modules/graphql-tag/index"' has no exported member 'gql'.)
I have run many, many apollo and angular npm installs, including npm install --save graphql-tag, trying install whatever I'm missing, doesn't seem to matter what I install.
What am I doing wrong?
Use the default export instead:
import gql from 'graphql-tag';
I see it. What is happening here is your code is trying to destructure gql off of the object that is exported out of graphql-tag, but the error is telling you there is no exported member of this name, meaning the exported object doesn't have a method of that name, or there are more than one object exported.
If you were to look in the code for graphql-tag, you would see it probably has a few export objects or it only has one that doesnt have a method called gql, so what you need to do is take gql directly, ie: without destructuring it, ie: without the { }.
This will be correct: import gql from 'graphql-tag'
You can see this all the time depending how you export and import things from modules.
Commit to memory that every time you see { something }, it is pulling something off an object.
Here is some sample code to illustrate:
const object = {
test: { name = 'Locohost' }
}
const { name } = object.test
console.log(name)

Resources