2015-08-17 23:56:29 +02:00
|
|
|
{-# LANGUAGE DataKinds #-}
|
|
|
|
{-# LANGUAGE DeriveGeneric #-}
|
2015-05-06 13:36:04 +02:00
|
|
|
{-# LANGUAGE FlexibleInstances #-}
|
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
2015-08-17 23:56:29 +02:00
|
|
|
{-# LANGUAGE TypeFamilies #-}
|
|
|
|
{-# LANGUAGE TypeOperators #-}
|
2015-05-10 13:39:18 +02:00
|
|
|
module T4 where
|
2015-05-06 13:36:04 +02:00
|
|
|
|
2015-08-17 23:56:29 +02:00
|
|
|
import Data.Aeson
|
|
|
|
import Data.Foldable (foldMap)
|
|
|
|
import GHC.Generics
|
|
|
|
import Lucid
|
|
|
|
import Network.Wai
|
|
|
|
import Servant
|
|
|
|
import Servant.HTML.Lucid
|
2015-05-06 13:36:04 +02:00
|
|
|
|
|
|
|
data Person = Person
|
|
|
|
{ firstName :: String
|
|
|
|
, lastName :: String
|
|
|
|
, age :: Int
|
|
|
|
} deriving Generic -- for the JSON instance
|
|
|
|
|
|
|
|
-- JSON serialization
|
|
|
|
instance ToJSON Person
|
|
|
|
|
|
|
|
-- HTML serialization of a single person
|
|
|
|
instance ToHtml Person where
|
2015-06-18 12:32:00 +02:00
|
|
|
toHtml person =
|
2015-05-06 13:36:04 +02:00
|
|
|
tr_ $ do
|
2015-06-18 12:32:00 +02:00
|
|
|
td_ (toHtml $ firstName person)
|
|
|
|
td_ (toHtml $ lastName person)
|
|
|
|
td_ (toHtml . show $ age person)
|
2015-05-06 13:36:04 +02:00
|
|
|
|
|
|
|
toHtmlRaw = toHtml
|
|
|
|
|
|
|
|
-- HTML serialization of a list of persons
|
|
|
|
instance ToHtml [Person] where
|
|
|
|
toHtml persons = table_ $ do
|
|
|
|
tr_ $ do
|
2015-06-18 12:32:00 +02:00
|
|
|
th_ "first name"
|
|
|
|
th_ "last name"
|
|
|
|
th_ "age"
|
2015-05-06 13:36:04 +02:00
|
|
|
|
|
|
|
foldMap toHtml persons
|
|
|
|
|
|
|
|
toHtmlRaw = toHtml
|
|
|
|
|
|
|
|
persons :: [Person]
|
|
|
|
persons =
|
|
|
|
[ Person "Isaac" "Newton" 372
|
|
|
|
, Person "Albert" "Einstein" 136
|
|
|
|
]
|
|
|
|
|
|
|
|
type PersonAPI = "persons" :> Get '[JSON, HTML] [Person]
|
|
|
|
|
|
|
|
personAPI :: Proxy PersonAPI
|
|
|
|
personAPI = Proxy
|
|
|
|
|
|
|
|
server :: Server PersonAPI
|
|
|
|
server = return persons
|
|
|
|
|
|
|
|
app :: Application
|
2016-01-07 12:51:30 +01:00
|
|
|
app = serve personAPI EmptyConfig server
|