3[](http://travis-ci.org/haskell-servant/servant-jquery)
4[](https://coveralls.io/r/haskell-servant/servant-jquery)
6
8This library lets you derive automatically (JQuery based) Javascript functions that let you query each endpoint of a *servant* webservice.
12Read more about the following example [here](https://github.com/haskell-servant/servant-jquery/tree/master/examples#examples).
15{-# LANGUAGE DataKinds #-}
16{-# LANGUAGE TypeOperators #-}
17{-# LANGUAGE DeriveGeneric #-}
18{-# LANGUAGE GeneralizedNewtypeDeriving #-}
20import Control.Concurrent.STM
21import Control.Monad.IO.Class
25import Network.Wai.Handler.Warp (run)
30-- * A simple Counter data type
31newtype Counter = Counter { value :: Int }
32 deriving (Generic, Show, Num)
34instance ToJSON Counter
36-- * Shared counter operations
38-- Creating a counter that starts from 0
39newCounter :: IO (TVar Counter)
40newCounter = newTVarIO 0
42-- Increasing the counter by 1
43counterPlusOne :: MonadIO m => TVar Counter -> m Counter
44counterPlusOne counter = liftIO . atomically $ do
45 oldValue <- readTVar counter
46 let newValue = oldValue + 1
47 writeTVar counter newValue
50currentValue :: MonadIO m => TVar Counter -> m Counter
51currentValue counter = liftIO $ readTVarIO counter
54type TestApi = "counter" :> Post Counter -- endpoint for increasing the counter
55 :<|> "counter" :> Get Counter -- endpoint to get the current value
56 :<|> Raw -- used for serving static files
58testApi :: Proxy TestApi
61-- * Server-side handler
63-- where our static files reside
68server :: TVar Counter -> Server TestApi
69server counter = counterPlusOne counter -- (+1) on the TVar
70 :<|> currentValue counter -- read the TVar
71 :<|> serveDirectory www -- serve static files
73runServer :: TVar Counter -- ^ shared variable for the counter
74 -> Int -- ^ port the server should listen on
76runServer var port = run port (serve testApi $ server var)
78-- * Generating the JQuery code
80incCounterJS :<|> currentValueJS :<|> _ = jquery testApi
82writeJS :: FilePath -> [AjaxReq] -> IO ()
83writeJS fp functions = writeFile fp $
84 concatMap generateJS functions
88 -- write the JS code to www/api.js at startup
89 writeJS (www </> "api.js")
90 [ incCounterJS, currentValueJS ]
92 -- setup a shared counter
95 -- 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