1{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE TypeOperators #-}
3{-# LANGUAGE DeriveGeneric #-}
4{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6import Control.Concurrent.STM
7import Control.Monad.IO.Class
11import Network.Wai.Handler.Warp (run)
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
36currentValue :: MonadIO m => TVar Counter -> m Counter
37currentValue counter = liftIO $ readTVarIO counter
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
47-- * Server-side handler
49-- where our static files reside
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
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
74 -- write the JS code to www/api.js at startup
75 writeJS (www </> "api.js")
76 [ incCounterJS, currentValueJS ]
78 -- setup a shared counter
81 -- listen to requests on port 8080
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list