Use AsyncLocalStorage to store a typeorm transaction in NestJS

1.1k Views Asked by At

I have a question regarding AsyncLocalStorage and Interceptors in NestJS.

Will there be any implications of storing a transaction (EntityManager) inside the AsyncLocalStorage? I created an interceptor to wrap my requests inside a transaction and I store the manager so that anything inside that request can use it.

My main concerns are:

  1. Is AsyncLocalStorage suitable to store this kind of complex objects?
  2. Can I encounter any unwanted behavior by unwrapping the request Observable into promise and then wrapping it again?
  3. Is there something else?

I'm running NestJS 8 using Express 4.17.3 with node 16.4.2

Here is the code of my interceptor:

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor
} from '@nestjs/common'
import { AsyncLocalStorage } from 'async_hooks'
import { from, lastValueFrom, Observable } from 'rxjs'
import { getManager } from 'typeorm'

const transactionStorage = new AsyncLocalStorage()

@Injectable()
export class TransactionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return from(
      getManager().transaction((manager) => {
        return transactionStorage.run(manager, () => {
          return lastValueFrom(next.handle())
        })
      })
    )
  }
}
0

There are 0 best solutions below