git.iko.soy/typeable/servant
on master help sign in
clean up servant-js significantly, simplify the API of the library a lot and document @freezeboy's sweet generators from #159 a bit in the main module of the library, Servant.JS along with how people should use the library.
commita2a466595129bf180b28c4ee90f46a83dde21c45 authorAlp Mestanogullari <alpmestan@gmail.com> dateWed 22 Jul 2015, 19:23 (11 years ago) parent0f15cb7
10 files changed+217−84
servant-examples/tutorial/T9.hs+1−1 servant-js/examples/counter.hs+31−30 servant-js/servant-js.cabal+1−1 servant-js/src/Servant/JS.hs+118−32 servant-js/src/Servant/JS/Angular.hs+22−12 servant-js/src/Servant/JS/Internal.hs+15−1 servant-js/src/Servant/JS/JQuery.hs+11 servant-js/src/Servant/JS/Vanilla.hs+12 servant-js/test/Servant/JSSpec.hs+5−7 servant-js/test/Servant/JSSpec/CustomHeaders.hs+1
servant-examples/tutorial/T9.hs+1−1
@@ -93,7 +93,7 @@ server' = server
9393 :<|> serveDirectory "tutorial/t9"
9494
9595apiJS :: String
96−apiJS = jsForAPI api generateJQueryJS
96+apiJS = jsForAPI api jquery
9797
9898writeJSFiles :: IO ()
9999writeJSFiles = do
servant-js/examples/counter.hs+31−30
@@ -12,8 +12,6 @@ import Network.Wai.Handler.Warp (run)
1212import Servant
1313import Servant.JS
1414import qualified Servant.JS as SJS
15−import qualified Servant.JS.Vanilla as JS
16−import qualified Servant.JS.JQuery as JQ
1715import qualified Servant.JS.Angular as NG
1816import System.FilePath
1917
@@ -43,55 +41,58 @@ currentValue counter = liftIO $ readTVarIO counter
4341-- * Our API type
4442type TestApi = "counter" :> Post '[JSON] Counter -- endpoint for increasing the counter
4543 :<|> "counter" :> Get '[JSON] Counter -- endpoint to get the current value
46− :<|> Raw -- used for serving static files
4744
45+type TestApi' = TestApi
46+ :<|> Raw -- used for serving static files
47+
48+-- this proxy only targets the proper endpoints of our API,
49+-- not the static file serving bit
4850testApi :: Proxy TestApi
4951testApi = Proxy
5052
53+-- this proxy targets everything
54+testApi' :: Proxy TestApi'
55+testApi' = Proxy
56+
5157-- * Server-side handler
5258
5359-- where our static files reside
5460www :: FilePath
5561www = "examples/www"
5662
57−-- defining handlers
63+-- defining handlers of our endpoints
5864server :: TVar Counter -> Server TestApi
5965server counter = counterPlusOne counter -- (+1) on the TVar
6066 :<|> currentValue counter -- read the TVar
61− :<|> serveDirectory www -- serve static files
67+
68+-- the whole server, including static file serving
69+server' :: TVar Counter -> Server TestApi'
70+server' counter = server counter
71+ :<|> serveDirectory www -- serve static files
6272
6373runServer :: TVar Counter -- ^ shared variable for the counter
6474 -> Int -- ^ port the server should listen on
6575 -> IO ()
66−runServer var port = run port (serve testApi $ server var)
67−
68−-- * Generating the JQuery code
69−incCounterJS :: AjaxReq
70−currentValueJS :: AjaxReq
71−incCounterJS :<|> currentValueJS :<|> _ = javascript testApi
72−
73−writeJS :: JavaScriptGenerator -> FilePath -> [AjaxReq] -> IO ()
74−writeJS gen fp functions = writeFile fp $
75− concatMap (\req -> generateJS req gen) functions
76−
77−writeServiceJS :: FilePath -> [AjaxReq] -> IO ()
78−writeServiceJS fp functions = writeFile fp $
79− NG.wrapInServiceWith (NG.defAngularOptions { NG.serviceName = "counterSvc" })
80− (defCommonGeneratorOptions { SJS.moduleName = "counterApp" }) functions
76+runServer var port = run port (serve testApi' $ server' var)
77+
78+writeServiceJS :: FilePath -> IO ()
79+writeServiceJS fp =
80+ writeJSForAPI testApi
81+ (angularServiceWith (NG.defAngularOptions { NG.serviceName = "counterSvc" })
82+ (defCommonGeneratorOptions { SJS.moduleName = "counterApp" })
83+ )
84+ fp
8185
8286main :: IO ()
8387main = do
8488 -- write the JS code to www/api.js at startup
85− writeJS JQ.generateJQueryJS (www </> "jquery" </> "api.js")
86− [ incCounterJS, currentValueJS ]
87− writeJS JS.generateVanillaJS (www </> "vanilla" </> "api.js")
88− [ incCounterJS, currentValueJS ]
89− writeJS (NG.generateAngularJS
90− NG.defAngularOptions) (www </> "angular" </> "api.js")
91− [ incCounterJS, currentValueJS ]
92− writeServiceJS
93− (www </> "angular" </> "api.service.js")
94− [ incCounterJS, currentValueJS ]
89+ writeJSForAPI testApi jquery (www </> "jquery" </> "api.js")
90+
91+ writeJSForAPI testApi vanillaJS (www </> "vanilla" </> "api.js")
92+
93+ writeJSForAPI testApi (angular defAngularOptions) (www </> "angular" </> "api.js")
94+
95+ writeServiceJS (www </> "angular" </> "api.service.js")
9596
9697 -- setup a shared counter
9798 cnt <- newCounter
servant-js/servant-js.cabal+1−1
@@ -38,7 +38,7 @@ library
3838 Servant.JS.Angular
3939 Servant.JS.JQuery
4040 Servant.JS.Vanilla
41− other-modules: Servant.JS.Internal
41+ Servant.JS.Internal
4242 build-depends: base >=4.5 && <5
4343 , charset
4444 , lens >= 4
servant-js/src/Servant/JS.hs+118−32
@@ -4,56 +4,140 @@
44{-# LANGUAGE FlexibleInstances #-}
55-----------------------------------------------------------------------------
66-- |
7−-- Module : Servant.JQuery
7+-- Module : Servant.JS
88-- License : BSD3
99-- Maintainer : Alp Mestanogullari <alpmestan@gmail.com>
1010-- Stability : experimental
1111-- Portability : non-portable
12+--
13+-- Generating Javascript code to query your APIs using vanilla Javascript,
14+-- Angular.js or JQuery.
15+--
16+-- Using this package is very simple. Say you have this API type around:
17+--
18+-- > type API = "users" :> Get '[JSON] [Users]
19+-- > :<|> "messages" :> Get '[JSON] [Message]
20+--
21+-- All you need to do to generate the Javascript code is to write a 'Proxy'
22+-- for this API type:
23+--
24+-- > api :: Proxy API
25+-- > api = Proxy
26+--
27+-- And pick one of the generators:
28+--
29+-- - 'vanillaJS' and 'vanillaJSWith' generate functions that use
30+-- /XMLHttpRequest/ to query your endpoints. The former just calls
31+-- the latter with default code-generation options.
32+-- - 'jquery' and 'jqueryWith' follow the same pattern except that they
33+-- generate functions that use /jQuery/'s AJAX functions.
34+-- - 'angular' and 'angularWith' do the same but use /Angular.js/'s $http
35+-- service. In addition, we provide 'angularService' and 'angularServiceWith'
36+-- which produce functions under an Angular service that your controlers
37+-- can depend on to query the API.
38+--
39+-- Let's keep it simple and produce vanilla Javascript code with the default options.
40+--
41+-- @
42+-- jsCode :: String
43+-- jsCode = 'jsForAPI' api 'vanillaJS'
44+-- @
45+--
46+-- That's it! If you want to write that code to a file:
47+--
48+-- @
49+-- writeJSCode :: IO ()
50+-- writeJSCode = 'writeJSForAPI' api 'vanillaJS' "./my_api.js"
51+-- @
52+--
53+-- If you want to customize the rendering options, take a look
54+-- at 'CommonGeneratorOptions' which are generic options common to all the
55+-- generators. the /xxxWith/ variants all take 'CommonGeneratorOptions' whereas
56+-- the /xxx/ versions use 'defCommonGeneratorOptions'. Once you have some custom
57+--
58+-- > myOptions :: 'CommonGeneratorOptions'
59+--
60+-- All you need to do to use it is to use 'vanillaJSWith' and pass it @myOptions@.
61+--
62+-- @
63+-- jsCodeWithMyOptions :: String
64+-- jsCodeWithMyOptions = 'jsForAPI' api ('vanillaJSWith' myOptions)
65+-- @
66+--
67+-- Follow the same pattern for any other generator.
68+--
69+-- /Note/: The Angular generators take an additional type of options,
70+-- namely 'AngularOptions', to let you tweak aspects of the code generation
71+-- that are specific to /Angular.js/.
1272module Servant.JS
13− ( javascript
14− , generateJS
15− , jsForAPI
16− , listFromAPI
17− , printJS
18− , module Servant.JS.Internal
19− , GenerateCode(..)
20− , CommonGeneratorOptions(..)
73+ ( -- * Generating javascript code from an API type
74+ jsForAPI
75+ , writeJSForAPI
76+ , JavaScriptGenerator
77+
78+ , -- * Options common to all generators
79+ CommonGeneratorOptions(..)
80+ , defCommonGeneratorOptions
81+
82+ , -- * Vanilla Javascript code generation
83+ vanillaJS
84+ , vanillaJSWith
85+
86+ , -- * JQuery code generation
87+ jquery
88+ , jqueryWith
89+
90+ , -- * Angular.js code generation
91+ angular
92+ , angularWith
93+ , angularService
94+ , angularServiceWith
95+ , AngularOptions(..)
96+ , defAngularOptions
97+
98+ , -- * Misc.
99+ listFromAPI
100+ , javascript
101+ , HasJS(..)
102+ , GenerateList(..)
103+ , AjaxReq
21104 ) where
22105
23106import Data.Proxy
24107import Servant.API
108+import Servant.JS.Angular
25109import Servant.JS.Internal
110+import Servant.JS.JQuery
111+import Servant.JS.Vanilla
26112
113+-- | Generate the data necessary to generate javascript code
114+-- for all the endpoints of an API, as ':<|>'-separated values
115+-- of type 'AjaxReq'.
27116javascript :: HasJS layout => Proxy layout -> JS layout
28117javascript p = javascriptFor p defReq
29118
30−printJS :: AjaxReq -> JavaScriptGenerator -> IO ()
31−printJS req gen = putStrLn (generateJS req gen)
32−
33−generateJS :: AjaxReq -> JavaScriptGenerator -> String
34−generateJS req gen = gen $ req
35−
36−-- | Utility class used by 'jsForAPI' which will
37−-- directly hand you all the Javascript code
38−-- instead of handing you a ':<|>'-separated list
39−-- of 'AjaxReq' like 'javascript' and then having to
40−-- use 'generateJS' on each 'AjaxReq'.
41−class GenerateCode reqs where
42− jsFor :: reqs -> JavaScriptGenerator -> String
43−
44−instance GenerateCode AjaxReq where
45− jsFor = generateJS
46−
47−instance GenerateCode rest => GenerateCode (AjaxReq :<|> rest) where
48− jsFor (req :<|> rest) gen = jsFor req gen ++ jsFor rest gen
49−
50119-- | Directly generate all the javascript functions for your API
51120-- from a 'Proxy' for your API type. You can then write it to
52121-- a file or integrate it in a page, for example.
53−jsForAPI :: (HasJS api, GenerateCode (JS api)) => Proxy api
54− -> JavaScriptGenerator -> String
55−jsForAPI p = jsFor (javascript p)
122+jsForAPI :: (HasJS api, GenerateList (JS api))
123+ => Proxy api -- ^ proxy for your API type
124+ -> JavaScriptGenerator -- ^ js code generator to use (angular, vanilla js, jquery, others)
125+ -> String -- ^ a string that you can embed in your pages or write to a file
126+jsForAPI p gen = gen (listFromAPI p)
127+
128+-- | Directly generate all the javascript functions for your API
129+-- from a 'Proxy' for your API type using the given generator
130+-- and write the resulting code to a file at the given path.
131+writeJSForAPI :: (HasJS api, GenerateList (JS api))
132+ => Proxy api -- ^ proxy for your API type
133+ -> JavaScriptGenerator -- ^ js code generator to use (angular, vanilla js, jquery, others)
134+ -> FilePath -- ^ path to the file you want to write the resulting javascript code into
135+ -> IO ()
136+writeJSForAPI p gen fp = writeFile fp (jsForAPI p gen)
56137
138+-- | Utility class used by 'jsForAPI' which computes
139+-- the data needed to generate a function for each endpoint
140+-- and hands it all back in a list.
57141class GenerateList reqs where
58142 generateList :: reqs -> [AjaxReq]
59143
@@ -63,5 +147,7 @@ instance GenerateList AjaxReq where
63147instance GenerateList rest => GenerateList (AjaxReq :<|> rest) where
64148 generateList (r :<|> rest) = r : generateList rest
65149
150+-- | Generate the necessary data for JS codegen as a list, each 'AjaxReq'
151+-- describing one endpoint from your API type.
66152listFromAPI :: (HasJS api, GenerateList (JS api)) => Proxy api -> [AjaxReq]
67153listFromAPI p = generateList (javascript p)
servant-js/src/Servant/JS/Angular.hs+22−12
@@ -5,6 +5,7 @@ import Control.Lens
55import Data.List
66import Data.Monoid
77
8+-- | Options specific to the angular code generator
89data AngularOptions = AngularOptions
910 { serviceName :: String -- ^ When generating code with wrapInService,
1011 -- name of the service to generate
@@ -24,28 +25,37 @@ defAngularOptions = AngularOptions
2425-- | Instead of simply generating top level functions, generates a service instance
2526-- on which your controllers can depend to access your API.
2627-- This variant uses default 'AngularOptions'.
27−wrapInService :: AngularOptions -> [AjaxReq] -> String
28−wrapInService ngOpts reqs = wrapInServiceWith ngOpts defCommonGeneratorOptions reqs
28+angularService :: AngularOptions -> JavaScriptGenerator
29+angularService ngOpts = angularServiceWith ngOpts defCommonGeneratorOptions
2930
3031-- | Instead of simply generating top level functions, generates a service instance
3132-- on which your controllers can depend to access your API
32−wrapInServiceWith :: AngularOptions -> CommonGeneratorOptions -> [AjaxReq] -> String
33−wrapInServiceWith ngOpts opts reqs =
34− ((prologue ngOpts) svc mName)
35− <> (intercalate "," $ map generator reqs) <>
36− (epilogue ngOpts)
33+angularServiceWith :: AngularOptions -> CommonGeneratorOptions -> JavaScriptGenerator
34+angularServiceWith ngOpts opts reqs =
35+ prologue ngOpts svc mName
36+ <> intercalate "," (map generator reqs) <>
37+ epilogue ngOpts
3738 where
38− generator req = (generateAngularJSWith ngOpts opts req)
39+ generator req = generateAngularJSWith ngOpts opts req
3940 svc = serviceName ngOpts
4041 mName = if null (moduleName opts)
4142 then "app."
42− else (moduleName opts) <> "."
43−
44−-- js codegen using $http service from Angular using default options
43+ else moduleName opts <> "."
44+
45+-- | Generate regular javacript functions that use
46+-- the $http service, using default values for 'CommonGeneratorOptions'.
47+angular :: AngularOptions -> JavaScriptGenerator
48+angular ngopts = angularWith ngopts defCommonGeneratorOptions
49+
50+-- | Generate regular javascript functions that use the $http service.
51+angularWith :: AngularOptions -> CommonGeneratorOptions -> JavaScriptGenerator
52+angularWith ngopts opts = intercalate "\n\n" . map (generateAngularJSWith ngopts opts)
53+
54+-- | js codegen using $http service from Angular using default options
4555generateAngularJS :: AngularOptions -> AjaxReq -> String
4656generateAngularJS ngOpts = generateAngularJSWith ngOpts defCommonGeneratorOptions
4757
48−-- js codegen using $http service from Angular
58+-- | js codegen using $http service from Angular
4959generateAngularJSWith :: AngularOptions -> CommonGeneratorOptions -> AjaxReq -> String
5060generateAngularJSWith ngOptions opts req = "\n" <>
5161 fname <> fsep <> " function(" <> argsStr <> ")\n"
servant-js/src/Servant/JS/Internal.hs+15−1
@@ -36,6 +36,17 @@ data CommonGeneratorOptions = CommonGeneratorOptions
3636 , moduleName :: String -- ^ namespace on which we define the js function (empty mean local var)
3737 }
3838
39+-- | Default options.
40+--
41+-- @
42+-- > defCommonGeneratorOptions = CommonGeneratorOptions
43+-- > { functionRenamer = id
44+-- > , requestBody = "body"
45+-- > , successCallback = "onSuccess"
46+-- > , errorCallback = "onError"
47+-- > , moduleName = ""
48+-- > }
49+-- @
3950defCommonGeneratorOptions :: CommonGeneratorOptions
4051defCommonGeneratorOptions = CommonGeneratorOptions
4152 {
@@ -48,7 +59,10 @@ defCommonGeneratorOptions = CommonGeneratorOptions
4859
4960type Arg = String
5061
51−type JavaScriptGenerator = AjaxReq -> String
62+-- A 'JavascriptGenerator' just takes the data found in the API type
63+-- for each endpoint and generates Javascript code in a String. Several
64+-- generators are available in this package.
65+type JavaScriptGenerator = [AjaxReq] -> String
5266
5367data Segment = Segment { _segment :: SegmentType, _matrix :: [MatrixArg] }
5468 deriving (Eq, Show)
servant-js/src/Servant/JS/JQuery.hs+11
@@ -5,6 +5,17 @@ import Control.Lens
55import Data.List
66import Data.Monoid
77
8+-- | Generate javascript functions that use the /jQuery/ library
9+-- to make the AJAX calls. Uses 'defCommonGeneratorOptions'
10+-- for the generator options.
11+jquery :: JavaScriptGenerator
12+jquery = concat . map generateJQueryJS
13+
14+-- | Generate javascript functions that use the /jQuery/ library
15+-- to make the AJAX calls. Lets you specify your own 'CommonGeneratorOptions'.
16+jqueryWith :: CommonGeneratorOptions -> JavaScriptGenerator
17+jqueryWith opts = concat . map (generateJQueryJSWith opts)
18+
819-- | js codegen using JQuery using default options
920generateJQueryJS :: AjaxReq -> String
1021generateJQueryJS = generateJQueryJSWith defCommonGeneratorOptions
servant-js/src/Servant/JS/Vanilla.hs+12
@@ -5,6 +5,18 @@ import Control.Lens
55import Data.List
66import Data.Monoid
77
8+-- | Generate vanilla javascript functions to make AJAX requests
9+-- to your API, using /XMLHttpRequest/. Uses 'defCommonGeneratorOptions'
10+-- for the 'CommonGeneratorOptions'.
11+vanillaJS :: JavaScriptGenerator
12+vanillaJS = concat . map generateVanillaJS
13+
14+-- | Generate vanilla javascript functions to make AJAX requests
15+-- to your API, using /XMLHttpRequest/. Lets you specify your
16+-- own options.
17+vanillaJSWith :: CommonGeneratorOptions -> JavaScriptGenerator
18+vanillaJSWith opts = concat . map (generateVanillaJSWith opts)
19+
820-- | js codegen using XmlHttpRequest using default generation options
921generateVanillaJS :: AjaxReq -> String
1022generateVanillaJS = generateVanillaJSWith defCommonGeneratorOptions
servant-js/test/Servant/JSSpec.hs+5−7
@@ -97,15 +97,13 @@ angularSpec test = describe specLabel $ do
9797 output _ = return ()
9898 testName = "MyService"
9999 ngOpts = NG.defAngularOptions { NG.serviceName = testName }
100− genJS req = NG.wrapInService ngOpts req
100+ genJS req = NG.angularService ngOpts req
101101
102102generateJSSpec :: TestNames -> (AjaxReq -> String) -> Spec
103103generateJSSpec n gen = describe specLabel $ do
104104 it "should generate valid javascript" $ do
105− let (postSimple :<|> getHasExtension ) = javascript (Proxy :: Proxy TestAPI)
106− parseFromString (genJS postSimple) `shouldSatisfy` isRight
107− parseFromString (genJS getHasExtension) `shouldSatisfy` isRight
108− output $ genJS getHasExtension
105+ let s = jsForAPI (Proxy :: Proxy TestAPI) (concat . map gen)
106+ parseFromString s `shouldSatisfy` isRight
109107
110108 it "should use non-empty function names" $ do
111109 let (_ :<|> topLevel) = javascript (Proxy :: Proxy TopLevelRawAPI)
@@ -141,13 +139,13 @@ generateJSSpec n gen = describe specLabel $ do
141139 jsText `shouldContain` (header n "X-WhatsForDinner" $ "\"I would like \" + headerXWhatsForDinner + \" with a cherry on top.\"")
142140
143141 it "can generate the whole javascript code string at once with jsForAPI" $ do
144− let jsStr = jsForAPI (Proxy :: Proxy TestAPI) gen
142+ let jsStr = jsForAPI (Proxy :: Proxy TestAPI) (concat . map gen)
145143 parseFromString jsStr `shouldSatisfy` isRight
146144 where
147145 specLabel = "generateJS(" ++ (show n) ++ ")"
148146 --output = print
149147 output _ = return ()
150− genJS req = generateJS req gen
148+ genJS req = gen req
151149 header :: TestNames -> String -> String -> String
152150 header v headerName headerValue
153151 | v `elem` [Vanilla, VanillaCustom] = "xhr.setRequestHeader(\"" ++ headerName ++ "\", " ++ headerValue ++ ");\n"
servant-js/test/Servant/JSSpec/CustomHeaders.hs+1
@@ -14,6 +14,7 @@ import Data.Proxy
1414import GHC.TypeLits
1515import Servant.API
1616import Servant.JS
17+import Servant.JS.Internal
1718
1819-- | This is a hypothetical combinator that fetches an Authorization header.
1920-- The symbol in the header denotes what kind of authentication we are