git.iko.soy/typeable/servant
on v0.4.4.4 help sign in
94 lines 2.7 kB history raw
1# servant-jquery
3![servant](https://raw.githubusercontent.com/haskell-servant/servant/master/servant.png)
5This library lets you derive automatically (JQuery based) Javascript functions that let you query each endpoint of a *servant* webservice.
7## Example
9Read more about the following example [here](https://github.com/haskell-servant/servant/tree/master/servant-jquery/tree/master/examples#examples).
11``` haskell
12{-# LANGUAGE DataKinds #-}
13{-# LANGUAGE TypeOperators #-}
14{-# LANGUAGE DeriveGeneric #-}
15{-# LANGUAGE GeneralizedNewtypeDeriving #-}
17import Control.Concurrent.STM
18import Control.Monad.IO.Class
19import Data.Aeson
20import Data.Proxy
21import GHC.Generics
22import Network.Wai.Handler.Warp (run)
23import Servant
24import Servant.JQuery
25import System.FilePath
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
45 return newValue
47currentValue :: MonadIO m => TVar Counter -> m Counter
48currentValue counter = liftIO $ readTVarIO counter
50-- * Our API type
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
56testApi = Proxy
58-- * Server-side handler
60-- where our static files reside
61www :: FilePath
62www = "examples/www"
64-- defining handlers
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
72 -> IO ()
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
83main :: IO ()
84main = do
85 -- write the JS code to www/api.js at startup
86 writeJS (www </> "api.js")
87 [ incCounterJS, currentValueJS ]
89 -- setup a shared counter
90 cnt <- newCounter
92 -- listen to requests on port 8080
93 runServer cnt 8080
94```