#I don't understand data-source and app.module => TypeOrmModule.forRoot()

2 messages · Page 1 of 1 (latest)

thin cedar
#

Hello,
in my project I setup a db in the app.module.ts like this :

@Module({
    imports: [
        ...
        TypeOrmModule.forRoot({
            type: 'postgres',
            host: process.env.DATABASE_HOST,
            port: parseInt(process.env.DATABASE_PORT),
            username: process.env.DATABASE_USER,
            password: process.env.DATABASE_PASSWORD,
            database: process.env.DATABASE_NAME,
            entities: [
                /* entities list */
            ],
            synchronize: true,
        }),
        /* modules list */
    ],
    controller: [AppController],
    providers: [AppService],
})
export class AppModule {}

But for some methods (datasource.getRepository() for exemple), I understand that a data-source is require. I did this :

dotenv.config();
const options: DataSourceOptions & SeederOptions = {
    type: 'postgres',
    username: process.env.DATABASE_USER,
    password: process.env.DATABASE_PASSWORD,
    database: process.env.DATABASE_NAME,
    entities: [/* entities list */],
    seeds: [
        'src/database/seeds/app.seeder{.ts,.js}',
        'src/database/seeds/users/*{.ts,.js}'
    ],
    factories: ['src/database/factories/**/*{.ts,.js}']
};

export const dataSource = new DataSource(options);

I find it strange to have to configure a connection to the database in two different places. That's why I don't think I've understood how to do it properly.
can someone please correct me?

thin cedar
#

Without the export const dataSource = new DataSource(options), my app.seeder.ts no longer works, even though the db is already configured in app.module.