Created
January 25, 2017 19:27
-
-
Save jandrewthompson/a3d88ca10aca9d2568080be210c96937 to your computer and use it in GitHub Desktop.
This works, but am I doing it right?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
{-# LANGUAGE DeriveGeneric #-} | |
module Main where | |
--import Web.Scotty | |
import Web.Scotty.Trans | |
import Data.Aeson (FromJSON, ToJSON) | |
import Data.Text.Lazy (Text) | |
import Data.Monoid ((<>)) | |
import GHC.Generics | |
import Control.Applicative | |
import Control.Monad.Reader | |
import Database.SQLite.Simple | |
import Database.SQLite.Simple.FromRow | |
data User = User { userId :: Int, userName :: String } deriving (Show, Generic) | |
instance FromRow User where | |
fromRow = User <$> field <*> field | |
instance ToRow User where | |
toRow (User id_ name_) = toRow (id_, name_) | |
instance ToJSON User | |
instance FromJSON User | |
type ScottyD = ScottyT Text (ReaderT (Connection) IO) | |
saveUser :: IO () | |
saveUser = do | |
conn <- open "test.db" | |
execute conn "insert into users (userId, userName) values (?, ?)" | |
(User {userId = 3, userName = "some guy"}) | |
close conn | |
getUser :: Connection -> Int -> IO [User] | |
getUser conn id = do | |
query_ conn "select * from users" :: IO [User] | |
matchesId :: Int -> User -> Bool | |
matchesId id user = userId user == id | |
routes :: ScottyD () | |
routes = do | |
get "/hello" $ do | |
text "hello world" | |
get "/people/:id" $ do | |
id <- param "id" | |
conn <- lift ask | |
users <- liftIO $ getUser conn id | |
json (filter (matchesId id) users) | |
get "/people" $ do | |
conn <- lift ask | |
users <- liftIO $ getUser conn 0 | |
json users | |
main :: IO () | |
main = do | |
putStr "Starting server..." | |
conn <- open "test.db" | |
let read = \r -> runReaderT r conn -- stuff the Connection into Reader | |
scottyT 3000 read routes | |
close conn | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment