Aliheym / typeorm-transactional

A Transactional Method Decorator for TypeORM that uses Async Local Storage or cls-hooked to handle and propagate transactions between different repositories and service methods.
MIT License
201 stars 27 forks source link

Error setting the datasource on the latest TypeOrm version #9

Closed danwunderlich closed 1 year ago

danwunderlich commented 1 year ago

Running TypeOrm 0.3.10 and seeing the below error on starting up my Nest application:

TypeError: Cannot read property 'manager' of undefined

Works fine on 0.3.7

(Great work btw, I'll stick to 0.3.7 for now)

Aliheym commented 1 year ago

Hi, could you please give an example of code where you get this error?

I tried my small example and also run tests with the newest TypeORM version and don't get such issue.

lbayas commented 1 year ago

FWIW I have seen the above issue as well, here is how I got around it in my nest app running typeorm w/ 0.3.10 and typeorm-transactional w/ 0.2.1

This following code fails for me, I took a quick look at the code and it looks like it should work as their is a instanceof check for DataSource, but some simple logging on my local machine yielded that this check was not triggering.

Here is my broken configuration:

    TypeOrmModule.forRootAsync({
      ...
      dataSourceFactory: async (options: DataSourceOptions) => {
        if (!options) {
          throw new Error('Invalid options passed');
        }

        // ERROR w/ Cannot read properties of undefined (reading 'manager')
        return addTransactionalDataSource(new DataSource(options));
      },
    }),

which yields the following error:

[Nest] 42741  - 10/08/2022, 4:05:04 PM   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...
TypeError: Cannot read properties of undefined (reading 'manager')

Here is my fixed configuration:

    TypeOrmModule.forRootAsync({
      ...
      dataSourceFactory: async (options: DataSourceOptions) => {
        if (!options) {
          throw new Error('Invalid options passed');
        }

        // WORKS for me
        return addTransactionalDataSource({
          name: 'default', // optional
          dataSource: new DataSource(options),
          patch: true, // optional
        });
      },
    }),

Hope that helps you @danwunderlich

I am not able to dive in too deep atm but there may be an issue with this check that, at least for me, is getting skipped: https://github.com/Aliheym/typeorm-transactional/blob/master/src/common/index.ts#L148

Aliheym commented 1 year ago

Hey guys. I fixed this bug in new version.

@lbayas thanks, for helping to debug this.