about summary refs log tree commit diff
path: root/src/API.hs
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2020-07-24T21·46+0100
committerWilliam Carroll <wpcarro@gmail.com>2020-07-24T21·48+0100
commit1d47e94bbe26479ffaaafecd27cdb83d072bfe01 (patch)
treef21dbed4627fc3c3c3ae6aa83d097fecd7da21ff /src/API.hs
parent660b8d43e5272e2b71b6092b4c879a82c4d861a8 (diff)
Integrate Persistent with Servant
Query my SQLite database from within my Servant handlers. Nothing I've written
is domain-specific to the business logic yet -- I'm just making sure everything
integrates.
Diffstat (limited to 'src/API.hs')
-rw-r--r--src/API.hs45
1 files changed, 14 insertions, 31 deletions
diff --git a/src/API.hs b/src/API.hs
index b2c7fd57d67f..b46ae5b3560f 100644
--- a/src/API.hs
+++ b/src/API.hs
@@ -1,39 +1,22 @@
 {-# LANGUAGE DataKinds #-}
-{-# LANGUAGE TypeApplications #-}
-{-# LANGUAGE DeriveGeneric #-}
-{-# LANGUAGE TypeOperators #-}
-{-# LANGUAGE KindSignatures #-}
 {-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE TypeOperators #-}
 --------------------------------------------------------------------------------
 module API where
 --------------------------------------------------------------------------------
-import qualified Data.Pool as DP
-import qualified Database.SQLite.Simple as DB
+import Data.Proxy
+import Data.Text
+import Database.Persist
+import Servant.API
 
-import Data.Aeson
-import GHC.Generics
-import GHC.TypeLits
-import Network.Wai.Handler.Warp
-import Servant
-import Control.Monad.IO.Class
+import qualified Types as T
 --------------------------------------------------------------------------------
 
-handlers :: DP.Pool DB.Connection -> Server API
-handlers pool = do
-  getHandler pool :<|> pure 0
-
-getHandler :: DP.Pool DB.Connection -> Handler Int
-getHandler pool =
-  DP.withResource pool $ \conn -> do
-     result <- liftIO $ DB.query_ conn "select 2 + 2"
-     case result of
-       [DB.Only x] -> pure x
-       _  -> pure (-1)
-
-type API = "number" :> Get '[JSON] Int
-      :<|> "other" :> Post '[JSON] Int
-
-main :: IO ()
-main = do
-  pool <- DP.createPool (DB.open "data.db") DB.close 1 0.5 1
-  run 3000 (serve (Proxy @ API) (handlers pool))
+type API = "user"
+           :> ReqBody '[JSON] T.User
+           :> Post '[JSON] (Maybe (Key T.User))
+      :<|> "user"
+           :> Capture "name" Text
+           :> Get  '[JSON] (Maybe T.User)