简体   繁体   中英

How to add a global transaction filter in play/scala?

I'm trying to set up a global filter to add transactionality to my entire app.

object TransactionFilter extends Filter {
    def apply(next: (RequestHeader) => Future[SimpleResult])(request: RequestHeader): Future[SimpleResult] = {
        next(request)
    }
}

I'm using squeryl, which uses blocks like so: transaction { ... }

object TransactionFilter extends Filter {
    def apply(next: (RequestHeader) => Future[SimpleResult])(request: RequestHeader): Future[SimpleResult] = {
        transaction { next(request) }
    }
}

Of course this doesn't work either, because it's only adding transactionality to the generation of the Future[SimpleResult].

I need the execution of the Future[SimpleResult] to be wrapped in a transaction { ... } block.

How do I do this? I have searched and searched.

On a side note, I'm not interested in using action composition for this, I've already got that working fine.

object TransactionFilter extends Filter {
  def apply(next: (RequestHeader) => Future[SimpleResult])(request: RequestHeader): Future[SimpleResult] = {
    // Begin transaction
    val tx = beginTx

    // Do the work
    val f = next(request)

    // Commit on success
    f onSuccess {
      case result => commitTx(tx)
    }

    // Rollback on failure
    f onFailure {
      case t => rollbackTx(tx)
    }

    f
  }

  def beginTx: Int = 42
  def commitTx(tx: Int) = {}
  def rollbackTx(tx: Int) = {}
}

Try to use slick 2.0 instead of squeryl.

In slick2 the TheadLocal session is renamed dynamic session and is not the default behaviour. The default one is an implicit session that can be used without problems with Futures

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM