Skip to content

Instantly share code, notes, and snippets.

@rschatz
Created February 26, 2015 21:40
Show Gist options
  • Save rschatz/5ef23f2b1f4055193293 to your computer and use it in GitHub Desktop.
Save rschatz/5ef23f2b1f4055193293 to your computer and use it in GitHub Desktop.
playing around with monads in servant
{-# LANGUAGE DataKinds, TypeOperators, OverloadedStrings #-}
import Servant.API
import Servant.Server
import Control.Monad.Trans.Either
import Data.Proxy
import Data.Aeson
data AuthResult = AuthResult { sessionCookie :: String, message :: String }
instance ToJSON AuthResult where
toJSON = undefined
data Whatever = Whatever
data HelloResponse = HelloResponse
instance ToJSON HelloResponse where
toJSON = undefined
newtype SessionMonad a = SessionMonad (IO a)
type AuthAPI = "login" :> QueryParam "user" String :> QueryParam "pass" String :> Get AuthResult
:<|> "logout" :> Get AuthResult
data AuthDB = AuthDB
runSession :: AuthDB -> SessionMonad a -> IO a
runSession _ (SessionMonad a) = a
loginHandler :: Maybe String -> Maybe String -> EitherT (Int,String) SessionMonad AuthResult
loginHandler = undefined
logoutHandler :: EitherT (Int,String) SessionMonad AuthResult
logoutHandler = undefined
--authHandler :: (Maybe String -> Maybe String -> EitherT (Int,String) SessionMonad AuthResult)
-- :<|> (EitherT (Int,String) SessionMonad AuthResult)
authHandler :: ServerT AuthAPI SessionMonad
authHandler = loginHandler :<|> logoutHandler
type MyProtectedAPI = "auth" :> AuthAPI
:<|> "hello" :> Get HelloResponse
myProtectedAPI :: Proxy MyProtectedAPI
myProtectedAPI = Proxy
helloHandler :: EitherT (Int,String) SessionMonad HelloResponse
helloHandler = undefined
myProtectedHandler :: ServerT MyProtectedAPI SessionMonad
myProtectedHandler = authHandler :<|> helloHandler
type MyOpenAPI = "public" :> Get Whatever
myOpenHandler :: Server MyOpenAPI
myOpenHandler = return Whatever
type MyAPI = MyProtectedAPI :<|> MyOpenAPI
myHandler :: AuthDB -> Server MyAPI
myHandler authDb = enter myProtectedAPI (runSession authDb) myProtectedHandler :<|> myOpenHandler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment