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