@@ -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)