0.0.26 • Published 5 years ago

@nest-kr/transaction v0.0.26

Weekly downloads
52
License
MIT
Repository
github
Last release
5 years ago

Nest-kr/transaction

This library handles transaction per request using decorator. It uses typeorm and cls-hooked internally and compatible with nest.js.

Installation

$ npm install --save @nest-kr/transaction

How to use

  • Configure module (provide Transaction and set TransactionMiddleware)
import { TransactionMiddleware, Transaction } from '@nest-kr/transaction';
import { getConnection } from 'typeorm';

@Module({
  controllers: [UserController],
  providers: [
    { provide: 'Transaction', useClass: Transaction },
    { provide: 'UserRepository', useClass: UserRepository },
    { provide: 'UserMapper', useClass: UserMapper },
    ... 
  ],
})
export class UserModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(TransactionMiddleware(getConnection))
      .forRoutes(UserController);
  }
}
  • Create Repository using Transaction
import {Injectable} from '@nestjs/common';
import { Transaction } from '@nest-kr/transaction';

@Injectable()
export class UserRepository {
    constructor(
        @Inject('UserMapper') private mapper: UserMapper,
        @Inject('Transaction') private transaction: Transaction,
    ){}
    
    async save(domain: User): Promise<void> {
        const entity = this.mapper.toEntity(domain);
        
        await this.transaction
          .entityManager()
          .getRepository(PageEntity)
          .save(entity);
    }
}
  • Use @Transactional for handling transaction per request.
@Injectable()
export class UserCommandService {
  constructor(
    @Inject('UserRepository') private userRepository: UserRepository,
    @Inject('UserFactory') private userFactory: UserFactory,
  ) {}

  @Transactional()
  async create(command: CreateUserCommand): Promise<CreateUserResult> {
    const user: User = this.userFactory.create(this.userRepository.nextId());
    await this.userRepository.save(user);

    return new CreateUserResult(user.id.key);
  }
}
0.0.26

5 years ago

0.0.25

5 years ago

0.0.24

5 years ago

0.0.23

5 years ago

0.0.22

5 years ago

0.0.21

5 years ago

0.0.20

5 years ago

0.0.19

5 years ago

0.0.18

5 years ago

0.0.17

5 years ago

0.0.16

5 years ago

0.0.15

5 years ago

0.0.14

5 years ago

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago

0.0.0

5 years ago