nestjs / TypeOrm database transaction

后端 未结 4 1586
遥遥无期
遥遥无期 2021-01-12 13:45

Assuming we have 2 services, A and B. Service A has a function doing the following:

  1. Validate the data
  2. Call a service B function, that makes changes to
4条回答
  •  忘掉有多难
    2021-01-12 13:58

    typeorm-transactional-cls-hooked uses CLS (Continuation Local Storage) to handle and propagate transactions between different repositories and service methods.

    @Injectable()
    export class PostService {
      constructor(
        private readonly authorRepository: AuthorRepository,
        private readonly postRepository: PostRepository,
      ) {}
    
      @Transactional() // will open a transaction if one doesn't already exist
      async createPost(authorUsername: string, message: string): Promise {
        const author = await this.authorRepository.create({ username: authorUsername });
        return this.postRepository.save({ message, author_id: author.id });
      }
    }
    

提交回复
热议问题