@@ -0,0 +1,77 @@
2+module Reflex.Dom.Xhr where
7+import Control.Monad.IO.Class
10+import qualified Data.Map as Map
12+import Data.Text (Text)
13+import qualified Data.Text as T
16+import GHCJS.DOM.XMLHttpRequest
18+import Reflex.Dom.Class
21+ = XhrRequest { _xhrRequest_method :: String
22+ , _xhrRequest_url :: String
23+ , _xhrRequest_config :: XhrRequestConfig
27+ = XhrRequestConfig { _xhrRequestConfig_headers :: Map String String
28+ , _xhrRequestConfig_user :: Maybe String
29+ , _xhrRequestConfig_password :: Maybe String
30+ , _xhrRequestConfig_responseType :: Maybe String
31+ , _xhrRequestConfig_sendData :: Maybe String
35+ = XhrResponse { _xhrResponse_body :: Maybe JSString
38+instance Default XhrRequestConfig where
39+ def = XhrRequestConfig { _xhrRequestConfig_headers = Map.empty
40+ , _xhrRequestConfig_user = Nothing
41+ , _xhrRequestConfig_password = Nothing
42+ , _xhrRequestConfig_responseType = Nothing
43+ , _xhrRequestConfig_sendData = Nothing
46+xhrRequest :: String -> String -> XhrRequestConfig -> XhrRequest
47+xhrRequest = XhrRequest
49+newXMLHttpRequest :: XhrRequest -> (XhrResponse -> IO a) -> IO XMLHttpRequest
50+newXMLHttpRequest req cb = do
51+ xhr <- xmlHttpRequestNew
52+ let c = _xhrRequest_config req
55+ (_xhrRequest_method req)
56+ (_xhrRequest_url req)
58+ (fromMaybe "" $ _xhrRequestConfig_user c)
59+ (fromMaybe "" $ _xhrRequestConfig_password c)
60+ iforM (_xhrRequestConfig_headers c) $ xmlHttpRequestSetRequestHeader xhr
61+ maybe (return ()) (xmlHttpRequestSetResponseType xhr . toJSString) (_xhrRequestConfig_responseType c)
62+ xmlHttpRequestOnreadystatechange xhr $ do
63+ readyState <- liftIO $ xmlHttpRequestGetReadyState xhr
66+ r <- liftIO $ xmlHttpRequestGetResponseText xhr
67+ _ <- liftIO $ cb $ XhrResponse r
70+ _ <- xmlHttpRequestSend xhr (_xhrRequestConfig_sendData c)
73+performRequestAsync :: MonadWidget t m => Event t XhrRequest -> m (Event t XhrResponse)
74+performRequestAsync req = performEventAsync $ ffor req $ \r cb -> do
75+ liftIO $ newXMLHttpRequest r cb