handle all requests in a transaction.

This commit is contained in:
Adam C. Baker
2014-10-10 17:16:56 -07:00
parent 57f4d478fc
commit e4669dcb37
3 changed files with 26 additions and 17 deletions
+10 -3
View File
@@ -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")]