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
213 stars 28 forks source link

Add method to delete datasource #6

Closed tjhiggins closed 2 years ago

tjhiggins commented 2 years ago

Needed to be able to delete the datasource for hot reloading via webpack to work with nestjs. Thanks for the fork!

example:

  TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [AppConfig],
      useFactory: async (app_config: AppConfig) => app_config.getConnectionOptions(),
      async dataSourceFactory(options) {
        if (!options) {
          throw new Error('Invalid options passed');
        }
        deleteDataSourceByName('default'); // Hot reloading requires we remove the previous patched data source
        return addTransactionalDataSource(new DataSource(options));
      },
    }),
Aliheym commented 2 years ago

Thanks for this PR.

You can also use something like that to prevent adding the data source several times:

import { addTransactionalDataSource, getDataSourceByName } from 'typeorm-transactional';

// ...

TypeOrmModule.forRootAsync({
    dataSourceFactory: async (options) => {
      return getDataSourceByName('default') || addTransactionalDataSource(new DataSource(options));
    },
  });
tjhiggins commented 2 years ago

Thanks for this PR.

You can also use something like that to prevent adding the data source several times:

import { addTransactionalDataSource, getDataSourceByName } from 'typeorm-transactional';

// ...

TypeOrmModule.forRootAsync({
    dataSourceFactory: async (options) => {
      return getDataSourceByName('default') || addTransactionalDataSource(new DataSource(options));
    },
  });

I tried that first, but the nestjs typeorm didn't like reusing the same datasource. I think there was a race condition during hot reloading where it would get closed by the previous server.

tjhiggins commented 2 years ago

Thanks for merging!