@nest-kr/transaction
v0.0.26
Published
```cli npm i @nest-kr/transaction ```
Downloads
31
Maintainers
Readme
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);
}
}