quotes-api/app/Main.hs

68 lines
1.9 KiB
Haskell
Raw Normal View History

2023-02-03 22:40:28 +00:00
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE DataKinds #-}
2023-02-27 18:16:29 +00:00
{-# LANGUAGE TypeOperators #-}
2023-02-03 13:45:16 +00:00
module Main where
2023-02-03 22:40:28 +00:00
import Database.SQLite.Simple
import Database.SQLite.Simple.QQ
import Network.Wai.Handler.Warp
import Data.Proxy
import Servant
import Control.Monad.IO.Class
2023-02-27 18:16:29 +00:00
import Api.Types
import qualified Parsers.KOReader as KO
2023-02-03 13:45:16 +00:00
main :: IO ()
main = do
putStrLn "Hello, Haskell!"
2023-02-03 22:40:28 +00:00
let dbfile = "quotes.db"
initDb dbfile
runApp dbfile
2023-02-27 18:16:29 +00:00
type API = "quotes" :> Get '[JSON] [Quote]
:<|> "quote" :> "random" :> Get '[JSON] Quote
:<|> "koreader" :> ReqBody '[JSON] KO.KoHighlight :> Post '[JSON] NoContent
2023-02-03 22:40:28 +00:00
api :: Proxy API
api = Proxy
initDb :: FilePath -> IO ()
initDb dbFile = withConnection dbFile $ \conn ->
execute_ conn
2023-02-27 18:16:29 +00:00
[sql|CREATE TABLE IF NOT EXISTS quotes ( quote text non null
, author text
, title text
, page text
, chapter text
, created_on integer);|]
2023-02-03 22:40:28 +00:00
2023-02-27 18:16:29 +00:00
-- | TODO: readerT
2023-02-03 22:40:28 +00:00
server :: FilePath -> Server API
2023-02-27 18:16:29 +00:00
server dbf = listQuotes dbf :<|> randomQuote dbf :<|> addKoReader dbf
-- | API begins here
randomQuote :: FilePath -> Handler Quote
randomQuote db = do
qts <- (liftIO $ withConnection db $ \c -> query_ c qry)
case (length qts) of
0 -> undefined
_ -> pure (head qts)
where
qry = [sql|SELECT * FROM quotes ORDER BY RANDOM();|]
2023-02-03 22:40:28 +00:00
listQuotes :: FilePath -> Handler [Quote]
listQuotes db = liftIO $ withConnection db $ \conn -> query_ conn [sql|SELECT * FROM quotes;|]
2023-02-27 18:16:29 +00:00
addKoReader :: FilePath -> KO.KoHighlight -> Handler NoContent
addKoReader db hl = do
liftIO $ withConnection db $ \c ->
executeMany c qry qts
pure NoContent
where
qry = [sql|INSERT INTO quotes VALUES (?,?,?,?,?,?);|]
qts = KO.parse hl
2023-02-03 22:40:28 +00:00
runApp :: FilePath -> IO ()
runApp dbfile = run 8081 (serve api $ server dbfile)