@@ -8,6 +8,8 @@
88{-# LANGUAGE ScopedTypeVariables #-}
99{-# LANGUAGE TupleSections #-}
1010
11+{-# LANGUAGE MultiParamTypeClasses #-}
12+{-# LANGUAGE FlexibleInstances #-}
1113module Servant.Common.Req where
1214
1315-------------------------------------------------------------------------------
@@ -15,8 +17,11 @@ import Control.Applicative (liftA2, liftA3)
1517import Control.Concurrent
1618import Control.Monad (join)
1719import Control.Monad.IO.Class (MonadIO, liftIO)
20+import Data.Aeson
1821import Data.Bifunctor (first)
19−import qualified Data.ByteString.Builder as Builder
22+import qualified Data.ByteString.Builder as BB
23+import qualified Data.ByteString as BS
24+import Data.ByteString.Lazy (ByteString)
2025import qualified Data.ByteString.Lazy.Char8 as BL
2126import qualified Data.Map as Map
2227import Data.Maybe (catMaybes, fromMaybe)
@@ -25,17 +30,24 @@ import Data.Monoid ((<>))
2530import Data.Proxy (Proxy(..))
2631import Data.Text (Text)
2732import qualified Data.Text as T
28−import qualified Data.Text.Encoding as TE
33+import qualified Data.Text.Lazy as TL
34+import qualified Data.Text.Encoding as T
2935import Data.Traversable (forM)
3036import Language.Javascript.JSaddle.Monad (JSM, MonadJSM, liftJSM)
37+import qualified Language.Javascript.JSaddle as JS
38+import qualified Data.JSString.Text as JS (lazyTextFromJSString)
3139import qualified Network.URI as N
3240import Reflex.Dom.Core hiding (tag)
3341import Servant.Common.BaseUrl (BaseUrl, showBaseUrl,
3442 SupportsServantReflex)
35−import Servant.API.ContentTypes (MimeUnrender(..), NoContent(..))
43+import Servant.API.ContentTypes ( NoContent(..), Accept, JSON
44+ , OctetStream, PlainText
45+ , FormUrlEncoded)
3646import Web.HttpApiData (ToHttpApiData(..))
47+import Web.FormUrlEncoded (FromForm, urlDecodeAsForm)
3748-------------------------------------------------------------------------------
3849import Servant.API.BasicAuth
50+-------------------------------------------------------------------------------
3951
4052
4153------------------------------------------------------------------------------
@@ -150,7 +162,7 @@ prependToPathParts p req =
150162 req { reqPathParts = p : reqPathParts req }
151163
152164addHeader :: (ToHttpApiData a, Reflex t) => Text -> Dynamic t (Either Text a) -> Req t -> Req t
153−addHeader name val req = req { headers = (name, (fmap . fmap) (TE.decodeUtf8 . toHeader) val) : headers req }
165+addHeader name val req = req { headers = (name, (fmap . fmap) (T.decodeUtf8 . toHeader) val) : headers req }
154166
155167
156168reqToReflexRequest
@@ -223,7 +235,7 @@ reqToReflexRequest reqMeth reqHost req =
223235 Map.insert "Content-Type" bCT (Map.fromList hs)
224236 , _xhrRequestConfig_user = Nothing
225237 , _xhrRequestConfig_password = Nothing
226− , _xhrRequestConfig_responseType = Just XhrResponseType_ArrayBuffer
238+ , _xhrRequestConfig_responseType = Nothing
227239 , _xhrRequestConfig_withCredentials = False
228240 , _xhrRequestConfig_responseHeaders = def
229241 }
@@ -235,7 +247,7 @@ reqToReflexRequest reqMeth reqHost req =
235247 Right hs -> Right $ def { _xhrRequestConfig_headers = Map.fromList hs
236248 , _xhrRequestConfig_user = Nothing
237249 , _xhrRequestConfig_password = Nothing
238− , _xhrRequestConfig_responseType = Just XhrResponseType_ArrayBuffer
250+ , _xhrRequestConfig_responseType = Nothing
239251 , _xhrRequestConfig_sendData = ""
240252 , _xhrRequestConfig_withCredentials = False
241253 }
@@ -245,8 +257,8 @@ reqToReflexRequest reqMeth reqHost req =
245257 mkAuth _ (Left e) = Left e
246258 mkAuth Nothing r = r
247259 mkAuth (Just (BasicAuthData u p)) (Right config) = Right $ config
248− { _xhrRequestConfig_user = Just $ TE.decodeUtf8 u
249− , _xhrRequestConfig_password = Just $ TE.decodeUtf8 p}
260+ { _xhrRequestConfig_user = Just $ T.decodeUtf8 u
261+ , _xhrRequestConfig_password = Just $ T.decodeUtf8 p}
250262
251263 addAuth :: Dynamic t (Either Text (XhrRequestConfig x))
252264 -> Dynamic t (Either Text (XhrRequestConfig x))
@@ -326,10 +338,9 @@ performSomeRequestsAsync' opts newXhr req = performEventAsync $ ffor req $ \hrs
326338 return ()
327339
328340
329−
330341type XhrPayload = T.Text
331342bytesToPayload :: BL.ByteString -> XhrPayload
332−bytesToPayload = TE.decodeUtf8 . BL.toStrict
343+bytesToPayload = T.decodeUtf8 . BL.toStrict
333344
334345
335346performRequestsCT
@@ -344,15 +355,14 @@ performRequestsCT
344355 -> m (Event t (f (ReqResult tag a)))
345356performRequestsCT ct reqMeth reqs reqHost opts trigger = do
346357 resps <- performRequests reqMeth reqs reqHost opts trigger
347− let decodeResp (Just (XhrResponseBody_ArrayBuffer x)) =
348− first T.pack .
349− mimeUnrender ct $
350− BL.fromStrict x
351− decodeResp _ = Left "No body"
358+ let decodeResp x = first T.pack
359+ . mimeUnrender ct
360+ . JS.textToJSString
361+ =<< note "No body text" (_xhrResponse_responseText x)
352362 return $ fmap
353363 (\(t,rs) -> ffor rs $ \r -> case r of
354364 Left e -> RequestFailure t e
355− Right g -> evalResponse (decodeResp . _xhrResponse_response) (t,g)
365+ Right g -> evalResponse decodeResp (t,g)
356366 )
357367 resps
358368
@@ -379,7 +389,7 @@ evalResponse
379389 :: (XhrResponse -> Either Text a)
380390 -> (tag, XhrResponse)
381391 -> ReqResult tag a
382−evalResponse decode (tag, xhr) =
392+evalResponse decodeRes (tag, xhr) =
383393 let status = _xhrResponse_status xhr
384394 okStatus = status >= 200 && status < 400
385395 errMsg = fromMaybe
@@ -390,20 +400,56 @@ evalResponse decode (tag, xhr) =
390400 then either
391401 (\e -> ResponseFailure tag e xhr)
392402 (\v -> ResponseSuccess tag v xhr)
393− (decode xhr)
403+ (decodeRes xhr)
394404 else ResponseFailure tag errMsg xhr
395405 in respPayld
396406
397407
408+-- | Similar to 'Servant.API.ContentType.MimeUnrender' but with the differnce that
409+-- the second argument expects a JSString instead of ByteString.
410+-- This can lead to better performance ghcjs.
411+class Accept contentType => MimeUnrender contentType a where
412+ mimeUnrender :: Proxy contentType -> JS.JSString -> Either String a
413+
414+instance FromJSON a => MimeUnrender JSON a where
415+ mimeUnrender _ = note "Failed to decode response" . jsonDecode
416+
417+-- | @urlDecodeAsForm@
418+-- Note that the @mimeUnrender p (mimeRender p x) == Right x@ law only
419+-- holds if every element of x is non-null (i.e., not @("", "")@)
420+instance FromForm a => MimeUnrender FormUrlEncoded a where
421+ mimeUnrender _ = first T.unpack . urlDecodeAsForm . BB.toLazyByteString . T.encodeUtf8Builder . JS.textFromJSString
422+
423+-- | @left show . TextL.decodeUtf8'@
424+instance MimeUnrender PlainText TL.Text where
425+ mimeUnrender _ = pure . JS.lazyTextFromJSString
426+
427+-- | @left show . TextS.decodeUtf8' . toStrict@
428+instance MimeUnrender PlainText T.Text where
429+ mimeUnrender _ = pure . JS.textFromJSString
430+
431+-- | @Right . BC.unpack@
432+instance MimeUnrender PlainText String where
433+ mimeUnrender _ = Right . T.unpack . JS.textFromJSString
434+
435+-- | @Right . id@
436+instance MimeUnrender OctetStream ByteString where
437+ mimeUnrender _ = pure . BB.toLazyByteString . T.encodeUtf8Builder . JS.textFromJSString
438+
439+-- | @Right . toStrict@
440+instance MimeUnrender OctetStream BS.ByteString where
441+ mimeUnrender _ = pure . T.encodeUtf8 . JS.textFromJSString
442+
398443note :: e -> Maybe a -> Either e a
399−note e = maybe (Left e) Right
444+note e Nothing = Left e
445+note _ (Just a) = Right a
400446
401447fmapL :: (e -> e') -> Either e a -> Either e' a
402448fmapL _ (Right a) = Right a
403449fmapL f (Left e) = Left (f e)
404450
405−builderToText :: Builder.Builder -> T.Text
406−builderToText = TE.decodeUtf8 . BL.toStrict . Builder.toLazyByteString
451+builderToText :: BB.Builder -> T.Text
452+builderToText = T.decodeUtf8 . BL.toStrict . BB.toLazyByteString
407453
408454escape :: T.Text -> T.Text
409−escape = T.pack . N.escapeURIString (not . N.isReserved) . T.unpack . TE.decodeUtf8 . BL.toStrict . Builder.toLazyByteString . toEncodedUrlPiece
455+escape = T.pack . N.escapeURIString (not . N.isReserved) . T.unpack . T.decodeUtf8 . BL.toStrict . BB.toLazyByteString . toEncodedUrlPiece