@@ -0,0 +1,88 @@
1+module Servant.JS.Axios where
3+import Servant.JS.Internal
5+import Data.Char (toLower)
9+-- | Generate regular javacript functions that use
10+-- the axios library, using default values for 'CommonGeneratorOptions'.
11+axios :: JavaScriptGenerator
12+axios = axiosWith defCommonGeneratorOptions
14+-- | Generate regular javascript functions that use the axios library.
15+axiosWith :: CommonGeneratorOptions -> JavaScriptGenerator
16+axiosWith opts = intercalate "\n\n" . map (generateAxiosJSWith opts)
18+-- | js codegen using axios library using default options
19+generateAxiosJS :: AjaxReq -> String
20+generateAxiosJS = generateAxiosJSWith defCommonGeneratorOptions
22+-- | js codegen using axios library
23+generateAxiosJSWith :: CommonGeneratorOptions -> AjaxReq -> String
24+generateAxiosJSWith opts req = "\n" <>
25+ fname <> " = function(" <> argsStr <> ")\n"
27+ <> " return axios." <> method <> "(" <> url <> ",\n"
33+ where argsStr = intercalate ", " args
35+ ++ map (view argName) queryparams
37+ ++ map (toValidFunctionName . (<>) "header" . headerArgName) hs
39+ captures = map captureArg
43+ hs = req ^. reqHeaders
45+ queryparams = req ^.. reqUrl.queryStr.traverse
47+ body = if req ^. reqBody
48+ then [requestBody opts]
53+ then " , data: JSON.stringify(body)\n" <>
54+ " , responseType: 'json'\n"
60+ else " , headers: { " ++ headersStr ++ " }\n"
62+ where headersStr = intercalate ", " $ map headerStr hs
63+ headerStr header = "\"" ++
64+ headerArgName header ++
65+ "\": " ++ show header
70+ else (moduleName opts) <> "."
72+ hasNoModule = null (moduleName opts)
74+ fname = namespace <> (functionRenamer opts $ req ^. funcName)
76+ method = map toLower $ req ^. reqMethod
77+ url = if url' == "'" then "'/'" else url'
84+ $ req ^.. reqUrl.path.traverse
86+ queryArgs = if null queryparams
88+ else " + '?" ++ jsParams queryparams