handle all requests in a transaction.
This commit is contained in:
+10
-3
@@ -5,12 +5,19 @@ module Middleware where
|
||||
|
||||
import Data.Aeson
|
||||
|
||||
import Database.HDBC (runRaw)
|
||||
import Database.HDBC.PostgreSQL (Connection)
|
||||
import Network.HTTP.Types.Header (hContentType)
|
||||
import Network.HTTP.Types.Status (status400)
|
||||
import Database.HDBC.Types (SqlError(..))
|
||||
import Control.Exception (catchJust)
|
||||
import Network.Wai
|
||||
import Network.Wai (Application, Request, Response, ResponseReceived, responseLBS)
|
||||
import Control.Exception (finally, catchJust)
|
||||
|
||||
type ResHandler = Response -> IO ResponseReceived
|
||||
|
||||
inTransaction :: Connection -> (Connection -> Application) -> Request -> ResHandler -> IO ResponseReceived
|
||||
inTransaction conn app req respond =
|
||||
finally (putStrLn "begin txn" >> runRaw conn "begin" >> app conn req respond) (putStrLn "commit txn" >> runRaw conn "commit")
|
||||
|
||||
instance ToJSON SqlError where
|
||||
toJSON t = object [
|
||||
@@ -21,7 +28,7 @@ instance ToJSON SqlError where
|
||||
]
|
||||
]
|
||||
|
||||
reportPgErrors :: Middleware
|
||||
reportPgErrors :: Application -> Request -> ResHandler -> IO ResponseReceived
|
||||
reportPgErrors app req respond =
|
||||
catchJust isPgException (app req respond) (
|
||||
respond . responseLBS status400 [(hContentType, "application/json")]
|
||||
|
||||
Reference in New Issue
Block a user