mtgsearch/src/Config.hs

69 lines
1.5 KiB
Haskell
Raw Normal View History

2023-03-16 14:54:10 +00:00
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Config
( getDataSeedPath, getDbPath, getBulkDataLink
2023-03-16 14:54:10 +00:00
) where
import Data.Aeson
import Data.Text
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as C8 (pack)
2023-03-16 14:54:10 +00:00
import GHC.Generics
2023-04-28 19:08:56 +00:00
import Control.Exception (try)
2023-04-28 19:08:56 +00:00
import GHC.IO.Exception
2023-03-16 14:54:10 +00:00
import System.IO.Strict as L
import Data.ByteString.Builder (lazyByteString)
2023-03-16 14:54:10 +00:00
data Config = Config{
dataseedpath :: String,
dbPath :: String,
bulkDataLink :: String
2023-03-16 14:54:10 +00:00
} 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 )
2023-04-28 19:08:56 +00:00
case a of
Right a -> return a
Left b -> error $ "Could not load configuration file"
2023-04-28 19:08:56 +00:00
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
2023-03-16 14:54:10 +00:00
getDataSeedPath = do
dataseedpath <$> getConfig
getDbPath ::IO String
2023-03-16 14:54:10 +00:00
getDbPath = do
dbPath <$> getConfig
getBulkDataLink :: IO (String)
getBulkDataLink = do
bulkDataLink <$> getConfig
2023-03-16 14:54:10 +00:00
extract :: IO (Maybe a) -> IO a
extract = (>>= maybe (ioError $ userError "Could not read config!") return)