3
5This library lets you derive automatically Javascript functions that let you query each endpoint of a *servant* webservice.
7It contains a powerful system allowing you to generate functions for several frameworks (Angular, AXios, JQuery) as well as
8vanilla (framework-free) javascript code.
12Read more about the following example [here](https://github.com/haskell-servant/servant/tree/master/servant-js/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 '[JSON] Counter -- endpoint for increasing the counter
55 :<|> "counter" :> Get '[JSON] Counter -- endpoint to get the current value
57type TestApi' = TestApi -- The API we want a JS handler for
58 :<|> Raw -- used for serving static files
60-- this proxy only targets the proper endpoints of our API,
61-- not the static file serving bit
62testApi :: Proxy TestApi
65-- this proxy targets everything
66testApi' :: Proxy TestApi'
69-- * Server-side handler
71-- where our static files reside
76server :: TVar Counter -> Server TestApi
77server counter = counterPlusOne counter -- (+1) on the TVar
78 :<|> currentValue counter -- read the TVar
80server' :: TVar Counter -> Server TestApi'
81server counter = server counter
82 :<|> serveDirectory www -- serve static files
84runServer :: TVar Counter -- ^ shared variable for the counter
85 -> Int -- ^ port the server should listen on
87runServer var port = run port (serve testApi' $ server' var)
91 -- write the JS code to www/api.js at startup
92 writeJSForAPI testApi jquery (www </> "api.js")
94 -- setup a shared counter
97 -- 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