module Servant.PostgreSQL.Prelude
( PGResult
, ToPGResult(..)
, toPGResult
, pgresultOfInts
, pgresultOfInt64
, module Servant.Context.PostgreSQL
) where
import Data.Foldable
import Data.Int
import Data.Monoid
import Database.PostgreSQL.Simple
import Servant.Context.PostgreSQL
import Servant.Prelude
import Servant.Response.Prelude
newtype PGResult o = PGResult { pgres :: Int64 }
deriving (Eq, Ord, Num, Show)
toPGResult :: ToPGResult r => IO r -> IO (PGResult o)
toPGResult = fmap fromRes
pgresultOfInts :: IO [Only Int] -> IO (PGResult o)
pgresultOfInts = toPGResult
pgresultOfInt64 :: IO Int64 -> IO (PGResult o)
pgresultOfInt64 = toPGResult
class ToPGResult r where
fromRes :: r -> PGResult o
instance ToPGResult Int64 where
fromRes = PGResult
instance ToPGResult [Only Int] where
fromRes ns = PGResult n
where n = getSum $ foldMap (Sum . fromIntegral . fromOnly) ns
instance Response (UpdateResponse Add) (PGResult Add) where
toResponse n = (response, statuscode)
where response = UpdateResponse successful msg
successful = n > 0
msg = if successful then "" else "no entry added"
statuscode = if successful then status201 else status400
instance Response (UpdateResponse Delete) (PGResult Delete) where
toResponse n = (response, statuscode)
where response = UpdateResponse successful msg
successful = n > 0
msg = if successful then "" else "couldn't delete: target entry doesn't exist"
statuscode = if successful then status200 else status404
instance Response (UpdateResponse Update) (PGResult Update) where
toResponse n = (response, statuscode)
where response = UpdateResponse successful msg
successful = n > 0
msg = if successful then "" else "couldn't update: target entry doesn't exist"
statuscode = if successful then status200 else status404