mtgsearch/src/Config.hs

63 lines
1.3 KiB
Haskell
Raw Normal View History

2023-03-16 14:54:10 +00:00
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Config
( getDataSeedPath, getDbPath
) where
import Data.Aeson
import Data.Text
import qualified Data.ByteString.Lazy as B
import GHC.Generics
2023-04-28 19:08:56 +00:00
import Control.Exception (try)
import Data.ByteString.Builder (lazyByteString)
import qualified Data.Aeson.Key as B
import qualified Data.Data as B
import GHC.IO.Exception
2023-03-16 14:54:10 +00:00
data Config = Config{
dataseedpath :: String,
dbPath :: String
} deriving (Show,Generic)
instance FromJSON Config
instance ToJSON Config
2023-04-28 19:08:56 +00:00
configFile = "./Config/config.json"
2023-03-16 14:54:10 +00:00
getJSON :: IO B.ByteString
2023-04-28 19:08:56 +00:00
getJSON = do
a <- try $ B.readFile configFile :: IO (Either IOException B.ByteString )
case a of
Right a -> return a
Left b -> error $ "Could not load configuration file"
2023-03-16 14:54:10 +00:00
readConfig :: IO (Maybe Config)
readConfig = do
result <- (eitherDecode <$> getJSON) :: IO (Either String Config)
case result of
Right conf ->
return (Just conf)
Left err -> do
putStrLn err
return Nothing
2023-04-28 19:08:56 +00:00
getConfig :: IO Config
2023-03-16 14:54:10 +00:00
getConfig = extract readConfig
getDataSeedPath ::IO (String)
getDataSeedPath = do
dataseedpath <$> getConfig
getDbPath ::IO (String)
getDbPath = do
dbPath <$> getConfig
extract :: IO (Maybe a) -> IO a
extract = (>>= maybe (ioError $ userError "Could not read config!") return)