Custom Transactional Decorator Challenger

문제

  • NestJSμ—μ„œ TypeORM을 μ‚¬μš©ν•˜μ—¬ νŠΈλžœμž­μ…˜μ„ κ΅¬ν˜„ν•  λ•Œ, ν•˜λ‚˜μ˜ λ©”μ„œλ“œκ°€ λ„ˆλ¬΄ λ§Žμ€ μ±…μž„μ„ κ°€μ§€κ³  μžˆλ‹€.

  • μ€‘λ³΅λœ μ½”λ“œκ°€ μ‘΄μž¬ν•œλ‹€.

circle-info

NestJS 곡식 λ¬Έμ„œμ—μ„œλŠ” Transactionsλ₯Ό κ΅¬ν˜„ν•˜λŠ” 두가지 방법

  • QueryRunner μ‚¬μš©

async createMany(users: User[]) {
  const queryRunner = this.dataSource.createQueryRunner();

  await queryRunner.connect();
  await queryRunner.startTransaction();
  try {
    await queryRunner.manager.save(users[0]);
    await queryRunner.manager.save(users[1]);

    await queryRunner.commitTransaction();
  } catch (err) {
    // since we have errors lets rollback the changes we made
    await queryRunner.rollbackTransaction();
  } finally {
    // you need to release a queryRunner which was manually instantiated
    await queryRunner.release();
  }
}
  • dataSource.transaction

async createMany(users: User[]) {
  await this.dataSource.transaction(async manager => {
    await manager.save(users[0]);
    await manager.save(users[1]);
  });
}

μ½”λ“œ

μœ„ μ½”λ“œμ—μ„œ try {} λ¬Έ μ™Έμ˜ μ½”λ“œ μ€‘λ³΅λœλ‹€.

ν•΄κ²° 방법

  • TypeScript의 λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜μ—¬ 곡톡 뢀뢄을 λΆ„λ¦¬ν•˜λŠ” 것이 κ°€λŠ₯ν•  κ²ƒμœΌλ‘œ 보인닀.

ν•΄κ²° κ³Όμ •

Step1

@Transactional() Decoratorλ₯Ό κ΅¬ν˜„ν•΄μ„œ 곡톡 λ‘œμ§μ„ Decoratorμ—μ„œ κ΅¬ν˜„ν•˜λ„λ‘ ν–ˆλ‹€.

  • λΉ„μ§€λ‹ˆμŠ€ 둜직

  • 곡톡 둜직(Transactional Decorator)

Step1 문제점

λΉ„μ¦ˆλ‹ˆμŠ€ 둜직의 Connect와 곡톡 둜직의 Connectκ°€ μ„œλ‘œ λ‹€λ₯΄κΈ° λ•Œλ¬Έμ—, λΉ„μ¦ˆλ‹ˆμŠ€ λ‘œμ§μ„ νŠΈλžœμž­μ…˜μœΌλ‘œ κ°μ‹ΈλŠ” 것이 λͺ©ν‘œμ˜€μœΌλ‚˜ 이λ₯Ό λ‹¬μ„±ν•˜μ§€ λͺ»ν–ˆλ‹€.

  • 곡톡 λ‘œμ§μ€ Connect 47

  • λΉ„μ§€λ‹ˆμŠ€ λ‘œμ§μ€ Conenct 48

Step2

λΉ„μ¦ˆλ‹ˆμŠ€ λ‘œμ§μ—μ„œ QueryRunnerλ₯Ό μ‚¬μš©ν•˜μ—¬ κ΅¬ν˜„ν•˜κ³ , λ°μ½”λ ˆμ΄ν„°λ₯Ό 톡해 이미 νŠΈλžœμž­μ…˜μ΄ μ‚¬μš© 쀑인지 ν™•μΈν•˜κ³ , ν•„μš”μ— 따라 μΆ”κ°€μ μœΌλ‘œ νŠΈλžœμž­μ…˜μ„ μ‹œμž‘ν•˜κ±°λ‚˜ QueryRunnerλ₯Ό μ£Όμž…ν•œλ‹€.

  • λΉ„μ§€λ‹ˆμŠ€ 둜직

  • 곡톡 둜직(Transactional Decorator)

  • κ²°κ³Ό

ν•˜λ‚˜μ˜ connect μ—μ„œ ν•˜λ‚˜μ˜ transactional μ•ˆμ—μ„œ λͺ¨λ“  둜직이 μ‹€ν–‰ν•œλ‹€.

κ²°λ‘ 

NestJS와 TypeORM을 μ‚¬μš©ν•˜μ—¬ νŠΈλžœμž­μ…˜ 관리λ₯Ό μœ„ν•œ μ½”λ“œ 쀑볡을 쀄이고, λ©”μ„œλ“œμ˜ μ±…μž„μ„ λΆ„μ‚°ν•˜λŠ” 방법을 νƒκ΅¬ν–ˆλ‹€.

  • Transactional Decorator의 λ„μž…

  • λΉ„μ¦ˆλ‹ˆμŠ€ 둜직과 νŠΈλžœμž­μ…˜ κ΄€λ¦¬μ˜ 뢄리

  • ν•˜λ‚˜μ˜ Connect λ‚΄μ—μ„œμ˜ νŠΈλžœμž­μ…˜ μ‹€ν–‰

결둠적으둜Transactional λ°μ½”λ ˆμ΄ν„°μ˜ μ‚¬μš©κ³Ό QueryRunner의 μ μ ˆν•œ 관리λ₯Ό 톡해, NestJS 및 TypeORM ν™˜κ²½μ—μ„œ νŠΈλžœμž­μ…˜μ„ 효율적으둜 관리할 수 μžˆλŠ” ꡬ쑰λ₯Ό κ΅¬μΆ•ν–ˆλ‹€. νŠΈλžœμž­μ…˜ 관리에 λŒ€ν•œ 쀑볡 μ½”λ“œλ₯Ό 쀄이고, λΉ„μ¦ˆλ‹ˆμŠ€ 둜직의 λͺ…ν™•μ„± 및 μœ μ§€λ³΄μˆ˜μ„±μ„ ν–₯μƒμ‹œμΌ°λ‹€.

λ¬Όλ‘ ,이 λ°μ½”λ ˆμ΄ν„° μ‚¬μš©ν•˜λŠ” 것이 μ–΄λ–€ 좔가적인 영ν–₯을 λ―ΈμΉ μ§€λŠ” 아직 λΆˆν™•μ‹€ν•˜λ‹€. ν…ŒμŠ€νŠΈμ½”λ“œλ₯Ό μž‘μ„±ν•˜κ³  μ§€μ†μ μœΌλ‘œ ν™•μΈν•΄μ„œ κ°œμ„  μž‘μ—…ν•  μ˜ˆμ •μ΄λ‹€.

Last updated