3
5This library lets you derive automatically (JQuery based) Javascript functions that let you query each endpoint of a *servant* webservice.
9Read more about the following example [here](https://github.com/haskell-servant/servant/tree/master/servant-jquery/tree/master/examples#examples).
12{-# LANGUAGE DataKinds #-}
13{-# LANGUAGE TypeOperators #-}
14{-# LANGUAGE DeriveGeneric #-}
15{-# LANGUAGE GeneralizedNewtypeDeriving #-}
17import Control.Concurrent.STM
18import Control.Monad.IO.Class
22import Network.Wai.Handler.Warp (run)
27-- * A simple Counter data type
28newtype Counter = Counter { value :: Int }
29 deriving (Generic, Show, Num)
31instance ToJSON Counter
33-- * Shared counter operations
35-- Creating a counter that starts from 0
36newCounter :: IO (TVar Counter)
37newCounter = newTVarIO 0
39-- Increasing the counter by 1
40counterPlusOne :: MonadIO m => TVar Counter -> m Counter
41counterPlusOne counter = liftIO . atomically $ do
42 oldValue <- readTVar counter
43 let newValue = oldValue + 1
44 writeTVar counter newValue
47currentValue :: MonadIO m => TVar Counter -> m Counter
48currentValue counter = liftIO $ readTVarIO counter
51type TestApi = "counter" :> Post Counter -- endpoint for increasing the counter
52 :<|> "counter" :> Get Counter -- endpoint to get the current value
53 :<|> Raw -- used for serving static files
55testApi :: Proxy TestApi
58-- * Server-side handler
60-- where our static files reside
65server :: TVar Counter -> Server TestApi
66server counter = counterPlusOne counter -- (+1) on the TVar
67 :<|> currentValue counter -- read the TVar
68 :<|> serveDirectory www -- serve static files
70runServer :: TVar Counter -- ^ shared variable for the counter
71 -> Int -- ^ port the server should listen on
73runServer var port = run port (serve testApi $ server var)
75-- * Generating the JQuery code
77incCounterJS :<|> currentValueJS :<|> _ = jquery testApi
79writeJS :: FilePath -> [AjaxReq] -> IO ()
80writeJS fp functions = writeFile fp $
81 concatMap generateJS functions
85 -- write the JS code to www/api.js at startup
86 writeJS (www </> "api.js")
87 [ incCounterJS, currentValueJS ]
89 -- setup a shared counter
92 -- 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