From 6f91d75e81f6c60216a76aa7bbe499607f7d6052 Mon Sep 17 00:00:00 2001 From: Li Haoyi Date: Tue, 2 Jan 2024 10:26:28 +0800 Subject: [PATCH] simplify cask scalasql integration --- example/todo/app/src/TodoServer.scala | 14 +++++--------- example/todoDb/app/src/TodoMvcDb.scala | 16 +++++++--------- example/todoDb/app/test/src/ExampleTests.scala | 3 +++ 3 files changed, 15 insertions(+), 18 deletions(-) diff --git a/example/todo/app/src/TodoServer.scala b/example/todo/app/src/TodoServer.scala index 9489b64141..6e80cd9650 100644 --- a/example/todo/app/src/TodoServer.scala +++ b/example/todo/app/src/TodoServer.scala @@ -16,16 +16,12 @@ object TodoServer extends cask.MainRoutes{ ) class transactional extends cask.RawDecorator{ - class TransactionFailed(val value: cask.router.Result.Error) extends Exception def wrapFunction(pctx: cask.Request, delegate: Delegate) = { - try sqliteClient.transaction( txn => - delegate(Map("txn" -> txn)) match{ - case cask.router.Result.Success(t) => cask.router.Result.Success(t) - case e: cask.router.Result.Error => throw new TransactionFailed(e) - } - ) - catch{case e: TransactionFailed => e.value} - + sqliteClient.transaction { txn => + val res = delegate(Map("txn" -> txn)) + if (res.isInstanceOf[cask.router.Result.Error]) txn.rollback() + res + } } } diff --git a/example/todoDb/app/src/TodoMvcDb.scala b/example/todoDb/app/src/TodoMvcDb.scala index b78781fa4a..eb3245f883 100644 --- a/example/todoDb/app/src/TodoMvcDb.scala +++ b/example/todoDb/app/src/TodoMvcDb.scala @@ -13,16 +13,12 @@ object TodoMvcDb extends cask.MainRoutes{ ) class transactional extends cask.RawDecorator{ - class TransactionFailed(val value: cask.router.Result.Error) extends Exception def wrapFunction(pctx: cask.Request, delegate: Delegate) = { - try sqliteClient.transaction( txn => - delegate(Map("txn" -> txn)) match{ - case cask.router.Result.Success(t) => cask.router.Result.Success(t) - case e: cask.router.Result.Error => throw new TransactionFailed(e) - } - ) - catch{case e: TransactionFailed => e.value} - + sqliteClient.transaction { txn => + val res = delegate(Map("txn" -> txn)) + if (res.isInstanceOf[cask.router.Result.Error]) txn.rollback() + res + } } } @@ -66,6 +62,8 @@ object TodoMvcDb extends cask.MainRoutes{ .returning(_.id) .single ) + + if (body == "FORCE FAILURE") throw new Exception("FORCE FAILURE BODY") } @transactional diff --git a/example/todoDb/app/test/src/ExampleTests.scala b/example/todoDb/app/test/src/ExampleTests.scala index f6c0d98e9e..0446a86bad 100644 --- a/example/todoDb/app/test/src/ExampleTests.scala +++ b/example/todoDb/app/test/src/ExampleTests.scala @@ -35,6 +35,9 @@ object ExampleTests extends TestSuite{ requests.post(s"$host/add", data = "new Task") + // Make sure endpoint failures do not commit their transaction + requests.post(s"$host/add", data = "FORCE FAILURE", check = false).statusCode ==> 500 + requests.get(s"$host/list/active").text() ==> """[{"id":3,"checked":false,"text":"new Task"}]"""