git.iko.soy/typeable/servant
on 0.2.2 help sign in
82 lines 2.3 kB history raw
1{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE TypeOperators #-}
3{-# LANGUAGE DeriveGeneric #-}
4{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6import Control.Concurrent.STM
7import Control.Monad.IO.Class
8import Data.Aeson
9import Data.Proxy
10import GHC.Generics
11import Network.Wai.Handler.Warp (run)
12import Servant
13import Servant.JQuery
14import System.FilePath
16-- * A simple Counter data type
17newtype Counter = Counter { value :: Int }
18 deriving (Generic, Show, Num)
20instance ToJSON Counter
22-- * Shared counter operations
24-- Creating a counter that starts from 0
25newCounter :: IO (TVar Counter)
26newCounter = newTVarIO 0
28-- Increasing the counter by 1
29counterPlusOne :: MonadIO m => TVar Counter -> m Counter
30counterPlusOne counter = liftIO . atomically $ do
31 oldValue <- readTVar counter
32 let newValue = oldValue + 1
33 writeTVar counter newValue
34 return newValue
36currentValue :: MonadIO m => TVar Counter -> m Counter
37currentValue counter = liftIO $ readTVarIO counter
39-- * Our API type
40type TestApi = "counter" :> Post Counter -- endpoint for increasing the counter
41 :<|> "counter" :> Get Counter -- endpoint to get the current value
42 :<|> Raw -- used for serving static files
44testApi :: Proxy TestApi
45testApi = Proxy
47-- * Server-side handler
49-- where our static files reside
50www :: FilePath
51www = "examples/www"
53-- defining handlers
54server :: TVar Counter -> Server TestApi
55server counter = counterPlusOne counter -- (+1) on the TVar
56 :<|> currentValue counter -- read the TVar
57 :<|> serveDirectory www -- serve static files
59runServer :: TVar Counter -- ^ shared variable for the counter
60 -> Int -- ^ port the server should listen on
61 -> IO ()
62runServer var port = run port (serve testApi $ server var)
64-- * Generating the JQuery code
66incCounterJS :<|> currentValueJS :<|> _ = jquery testApi
68writeJS :: FilePath -> [AjaxReq] -> IO ()
69writeJS fp functions = writeFile fp $
70 concatMap generateJS functions
72main :: IO ()
73main = do
74 -- write the JS code to www/api.js at startup
75 writeJS (www </> "api.js")
76 [ incCounterJS, currentValueJS ]
78 -- setup a shared counter
79 cnt <- newCounter
81 -- listen to requests on port 8080
82 runServer cnt 8080