packages feed

lucienne-0.0.1: Lucienne/ConnectionReader.hs

module Lucienne.ConnectionReader
  (Connection, ConnectionReader, accessDb, runConnectionReader)
where

import           Control.Monad.Reader (ReaderT,ask,liftIO,runReaderT)
import           Data.Char (toLower)
import qualified Data.CompactString.UTF8 as CS
import           Database.MongoDB (Pipe,Action,Database)
import qualified Database.MongoDB as M
import           Lucienne.Constant (programName)

type Connection = Pipe
type ConnectionReader = ReaderT Connection IO

database :: Database
database = CS.pack $ map toLower programName

accessDb :: Action IO a -> ConnectionReader a
accessDb action = do
  connection <- ask
  result <- liftIO $ M.access connection M.master database action
  case result of
    Right r -> return r
    Left l -> error $ "while accessing database: " ++ show l

runConnectionReader :: Connection -> ConnectionReader a -> IO a
runConnectionReader connection reader = runReaderT reader connection