Skip to content

Transactions does not work with multi tenant application #93

Open
@gcherem

Description

@gcherem

First of all, thank you for this library. It's a must-have.

I am using nest.js to create a multi tenant application, so the module creates the connection dynamically and injects into the service, and then I get the repository like this:

export class SurveyService {
  public repository: Repository<SurveyEntity>;

  constructor(
     @Inject(TENANT_CONNECTION) private connection,
     private surveyAttributeService: SurveyAttributeService
  ) { 
        this.repository = await this.connection.getRepository(SurveyEntity);  // <--- here
     }

  @Transactional()
  create(data): Promise<SurveyEntity> {
     const survey = this.repository.create(data);
     const savedSurvey = await this.repository.save(survey);
     if (data.attributes) {
       await this.surveyAttributeService.createFromArray(savedSurvey, data.attributes)
       // if an error occurs here, there is no rollback
     }
     return savedSurvey;
  }
}

The main.ts is:

import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger, ValidationPipe } from '@nestjs/common';
import { initializeTransactionalContext, patchTypeORMRepositoryWithBaseRepository } from 'typeorm-transactional-cls-hooked';
import * as compression from 'compression';
import { GqlRolesGuard } from './common/guards/gql-roles.guard';
import dotenvFlow = require('dotenv-flow');
import { ApolloErrorFilter } from './common/filters/apollo-error.filter';
import 'reflect-metadata';

async function bootstrap() {
  dotenvFlow.config({path: 'env'});
  initializeTransactionalContext(); // Initialize cls-hooked
  patchTypeORMRepositoryWithBaseRepository(); // patch Repository with BaseRepository.
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalGuards(new GqlRolesGuard(new Reflector()));
  app.use(compression()); // enable gzip
  app.useGlobalFilters(new ApolloErrorFilter());
  await app.listen(process.env.APP_PORT);
  Logger.log(`Server is running on: ${await app.getUrl()}`);
}
bootstrap();

Although my application works fine, transactions just don't work. Am I missing something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions