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