Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeOrmModule.forRoot() should accept connection name #66

Open
IntellectProductions opened this issue Feb 28, 2019 · 13 comments
Open

TypeOrmModule.forRoot() should accept connection name #66

IntellectProductions opened this issue Feb 28, 2019 · 13 comments

Comments

@IntellectProductions
Copy link

IntellectProductions commented Feb 28, 2019

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

TypeOrmModule.forRoot('default') is throwing as invalid code even though in the documentation states that it accepts the same arguments as createConnection() does in Typeorm.

[{
  "name": "default",
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "",
  "password": "",
  "database": "",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": false,
  "migrationsTableName": "migrations",
  "migrations": ["src/database/migrations/*{.ts,.js}"],
  "cli": {
    "migrationsDir": "src/database/migrations"
  }
}, {
  "name": "seed",
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "",
  "password": "",
  "database": "",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": false,
  "migrationsTableName": "seeds",
  "migrations": ["src/database/seeds/*{.ts,.js}"],
  "cli": {
    "migrationsDir": "src/database/seeds"
  }
}]

Expected behavior

It should pick the connection name from your ormconfig.js or json file like Typeorm does.

What is the motivation / use case for changing the behavior?

To stay up to date with Typeorm's codebase.

Environment


Nest version: 5.7.3

 
For Tooling issues:
- Node version: 10.5.0  
- Platform:  Mac 
@bhaidar
Copy link

bhaidar commented Mar 4, 2019

@IntellectProductions Is this only to stay up to date with Typeorm's codebase or/and to configure @nestjs/typeorm to create a specific connection by name?

I am facing the same issue now. My ormconfig.json has multiple connections and I cannot find a way to instruct it to use this connection or that.

cc: @kamilmysliwiec

@IntellectProductions
Copy link
Author

@bhaidar I hate the way I'm doing it now, but I'm basically duplicating my config inside my forRoot() method for the connection I want to use. I'm not very familiar with Typeorm's base code to actually try to do a PR or anything of that nature as much as I want to!

@pxr64
Copy link

pxr64 commented Aug 1, 2019

Same issue here, I cannot get 2 connections running by using the ormconfig.json config.

Is there any way to enhance this module so that it can support this?

@dsbert
Copy link
Contributor

dsbert commented Mar 11, 2020

Edit: I just realized this issue is specifically for loading from the ormconfig.json file but I will leave this comment in case anyone finds it useful and chooses to use a different way of configuring the connections.

This works for us but the documentation is definitely unclear on this point. Note that the connection name is passed outside of the connection configuration object.

const connectionName = 'other';

TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      name: connectionName,
      useFactory: async (configService: ConfigService) => {
        return {
          ...configService.get<ConnectionOptions>(connectionName),
          entities: [__dirname + '/**/*.entity.{js,ts}'],
        };
      },
    }),

@acepace
Copy link

acepace commented Apr 9, 2020

@dsbert I'm still not sure, are you suggesting I pass in a dummy name and convince nestjs/typeorm to load the correct configuration from ormconfig.json?

@dsbert
Copy link
Contributor

dsbert commented Apr 10, 2020

@acepace No, the important thing is that when calling forRootAsync, the connection name has to be passed as a separate parameter outside of the connection options. So if you are just passing in the ormconfig.json, that won't work. You also need to set the connection name explicitly. You don't need to do this if you are calling forRoot. Here is an example.

TypeOrmModule.forRoot(
	{
      name: 'conn1', // This field sets the connection when calling forRoot
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
      entities: [],
      synchronize: true,
    }
),
TypeOrmModule.forRootAsync(
      name: 'conn2', // This field sets the connection when calling forRootAsync
      useFactory: () => {
      return {
        name: 'conn2', // This field is ignored when calling forRootAsync
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        username: 'root',
        password: 'root',
        database: 'test',
        entities: [],
        synchronize: true,
      };
    },
),

@abhi18av
Copy link

@dsbert , thanks for the tip here!

I recently came across a similar issue, I'm simply relying on the forRoot and when I use the cms ( or engine) database and entity alone everything seems to work fine but when combined together, the connection which comes after, doesn't respond at all.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CmsTeamModule } from './modules/wcms/CmsTeam/CmsTeam.module';
import { EngTrophyModule } from './modules/engine/EngTrophy/EngTrophy.module';


@Module({
  imports: [
    TypeOrmModule.forRoot({
      'name': 'wcms',
      'type': 'mysql',
      'host': 'localhost',
      'port': 3306,
      'username': 'ci',
      'password': 'ci',
      'database': 'ci_wcms',
      'entities': [
        'dist/**/*.entity.js',
      ],
      'synchronize': false,
        'logging': true,
      },
    ),

    CmsTeamModule,


    TypeOrmModule.forRoot({
        'type': 'mysql',
        'host': 'localhost',
        'port': 3306,
        'username': 'ci',
        'password': 'ci',
        'database': 'ci_engine',
        'entities': [
          'dist/**/*.entity.js',
        ],
        'synchronize': false,
        'logging': true,
      },
    ),

    EngTrophyModule,

  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Am I making an obvious mistake here?

@kevinelliott
Copy link

Any update here? I'm seeing some oddities around this too.

@taeger100
Copy link

[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

@CatsMiaow
Copy link

// Database Default
TypeOrmModule.forRootAsync({
  useFactory: async (config: ConfigService) => ({
    entities: [`${__dirname}/entity/!(foo)/*.{js,ts}`],
    subscribers: [`${__dirname}/subscriber/!(foo)/*.{js,ts}`],
    migrations: [`${__dirname}/migration/!(foo)/*.{js,ts}`],
    ...config.get('db')[0],
  }),
  inject: [ConfigService],
}),
// Database Foo
TypeOrmModule.forRootAsync({
  name: 'foo',
  useFactory: async (config: ConfigService) => ({
    entities: [`${__dirname}/entity/foo/*.{js,ts}`],
    subscribers: [`${__dirname}/subscriber/foo/*.{js,ts}`],
    migrations: [`${__dirname}/migration/foo/*.{js,ts}`],
    ...config.get('db')[1],
  }),
  inject: [ConfigService],
}),

The above code has no problem running(nest start --watch), but testing gives an error.

let app: INestApplication;
let httpServer: unknown;

beforeAll(async () => {
  const moduleFixture = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();

  app = moduleFixture.createNestApplication();
  await app.init();

  httpServer = app.getHttpServer();
});

image

// Database Foo
TypeOrmModule.forRootAsync({
  name: 'foo',
  useFactory: async (config: ConfigService) => ({
    name: 'foo',
    entities: [`${__dirname}/entity/foo/*.{js,ts}`],
    subscribers: [`${__dirname}/subscriber/foo/*.{js,ts}`],
    migrations: [`${__dirname}/migration/foo/*.{js,ts}`],
    ...config.get('db')[1],
  }),
  inject: [ConfigService],
}),

Add name inside the useFactory as above also solved the problem.

getConnectionToken(this.options as ConnectionOptions) as Type<Connection>,

This error occurs because the name cannot be found in this.options in the code above.
It seems that the name value entered in forRootAsync needs to be added to this.options

@joaogolias
Copy link

joaogolias commented Oct 27, 2020

+1 for connection name support

@omidh28
Copy link

omidh28 commented Apr 11, 2021

I don't get it, I'm already using named connections for a long time in my side project. How is it an issue?

@fadeevab
Copy link

Seems like it won't happen, see the comment: #1030 (comment)

@nestjs nestjs locked as too heated and limited conversation to collaborators Jan 24, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests