git.iko.soy/typeable/servant
on master help sign in
Merge pull request #14 from haskell-servant/api-to-js-code-string

add a jsForAPI function that takes an API type proxy and generates js fu...

commit6a11656aa7a9a1edfd55d98d6bf66faa03a59575 authorAlp Mestanogullari <alpmestan@gmail.com> dateMon 20 Apr 2015, 11:40 (11 years ago) parent9838aca95a120f
4 files changed+29−1
CHANGELOG.md+1 servant-jquery.cabal+1−1 src/Servant/JQuery.hs+23 test/Servant/JQuerySpec.hs+4
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-----
servant-jquery.cabal+1−1
@@ -74,5 +74,5 @@ test-suite spec
7474 , servant
7575 , hspec >= 2.0
7676 , hspec-expectations
77− , language-ecmascript == 0.16.*
77+ , language-ecmascript >= 0.16
7878 default-language: Haskell2010
src/Servant/JQuery.hs+23
@@ -13,8 +13,10 @@
1313module Servant.JQuery
1414 ( jquery
1515 , generateJS
16+ , jsForAPI
1617 , printJS
1718 , module Servant.JQuery.Internal
19+ , GenerateCode(..)
1820 ) where
1921
2022import Control.Lens
@@ -92,3 +94,24 @@ generateJS req = "\n" <>
9294
9395printJS :: AjaxReq -> IO ()
9496printJS = 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 (Canonicalize api), GenerateCode (JQ api))
116+ => Proxy api -> String
117+jsForAPI p = jsFor (jquery p)
test/Servant/JQuerySpec.hs+4
@@ -90,3 +90,7 @@ generateJSSpec = describe "generateJS" $ do
9090 parseFromString jsText `shouldSatisfy` isRight
9191 jsText `shouldContain` "headerXWhatsForDinner"
9292 jsText `shouldContain` "headers: { \"X-WhatsForDinner\": \"I would like \" + headerXWhatsForDinner + \" with a cherry on top.\" }\n"
93+
94+ it "can generate the whole javascript code string at once with jsForAPI" $ do
95+ let jsStr = jsForAPI (Proxy :: Proxy TestAPI)
96+ parseFromString jsStr `shouldSatisfy` isRight