git.iko.soy/typeable/servant
on master help sign in
add a jsForAPI function that takes an API type proxy and generates js functions for each endpoint, collecting the result in a big String. fixes #12
commit21b6e96891d8281b164e843e5195759eaae39817 authorAlp Mestanogullari <alpmestan@gmail.com> dateSun 19 Apr 2015, 10:07 (11 years ago) parent8c6f327
2 files changed+26
CHANGELOG.md+1 src/Servant/JQuery.hs+25
CHANGELOG.md+1
@@ -3,6 +3,7 @@
33* Extend `HeaderArg` to support more advanced HTTP header handling (https://github.com/haskell-servant/servant-jquery/pull/6)
44* Support content-type aware combinators (but require that endpoints support JSON)
55* Add support for Matrix params (https://github.com/haskell-servant/servant-jquery/pull/11)
6+* Add functions that directly generate the Javascript code from the API type without having to manually pattern match on the result.
67
780.2.2
89-----
src/Servant/JQuery.hs+25
@@ -1,5 +1,6 @@
11{-# LANGUAGE DataKinds #-}
22{-# LANGUAGE TypeOperators #-}
3+{-# LANGUAGE FlexibleContexts #-}
34{-# LANGUAGE FlexibleInstances #-}
45-----------------------------------------------------------------------------
56-- |
@@ -12,14 +13,17 @@
1213module Servant.JQuery
1314 ( jquery
1415 , generateJS
16+ , jsForAPI
1517 , printJS
1618 , module Servant.JQuery.Internal
19+ , GenerateCode(..)
1720 ) where
1821
1922import Control.Lens
2023import Data.List
2124import Data.Monoid
2225import Data.Proxy
26+import Servant.API
2327import Servant.JQuery.Internal
2428
2529jquery :: HasJQ layout => Proxy layout -> JQ layout
@@ -90,3 +94,24 @@ generateJS req = "\n" <>
9094
9195printJS :: AjaxReq -> IO ()
9296printJS = putStrLn . generateJS
97+
98+-- | Utility class used by 'jsForAPI' which will
99+-- directly hand you all the Javascript code
100+-- instead of handing you a ':<|>'-separated list
101+-- of 'AjaxReq' like 'jquery' and then having to
102+-- use 'generateJS' on each 'AjaxReq'.
103+class GenerateCode reqs where
104+ jsFor :: reqs -> String
105+
106+instance GenerateCode AjaxReq where
107+ jsFor = generateJS
108+
109+instance GenerateCode rest => GenerateCode (AjaxReq :<|> rest) where
110+ jsFor (req :<|> rest) = jsFor req ++ jsFor rest
111+
112+-- | Directly generate all the javascript functions for your API
113+-- from a 'Proxy' for your API type. You can then write it to
114+-- a file or integrate it in a page, for example.
115+jsForAPI :: (HasJQ api, GenerateCode (JQ api))
116+ => Proxy api -> String
117+jsForAPI p = jsFor (jquery p)