1818{-# LANGUAGE FlexibleContexts #-}
1919{-# LANGUAGE JavaScriptFFI #-}
2020{-# LANGUAGE RecordWildCards #-}
21- module Solga.Client.GHCJS where
22- {-
21+ module Solga.Client.GHCJS
2322 ( Client (.. )
2423 , SomeRequestData (.. )
2524 , choose
2625 , RawRequest (.. )
2726 , ToSegment (.. )
2827 , WithData (.. )
2928 , GetResponse (.. )
29+ , JSONResponse (.. )
3030 ) where
31- -}
3231
3332import Data.Kind
3433import Data.Proxy
@@ -43,9 +42,8 @@ import Data.Typeable (Typeable)
4342import qualified Data.DList as DList
4443import Data.DList (DList )
4544import Data.String (fromString )
46- import qualified JavaScript.JSON.Types.Class as Json
47- import qualified JavaScript.JSON.Types.Internal as Json
48- import GHCJS.Types (Immutable )
45+ import qualified JavaScript.JSValJSON as Json
46+ import Data.Traversable (for )
4947
5048import Solga.Core hiding (Header )
5149
@@ -172,16 +170,21 @@ instance (Client next, KnownSymbol method) => Client (Method method next) where
172170
173171newtype GetResponse resp a b = GetResponse { unGetResponse :: Xhr. Response resp -> a -> IO b }
174172
173+ newtype JSONResponse = JSONResponse { unJSONResponse :: Json. Value}
174+
175+ instance Xhr. ResponseType JSONResponse where
176+ getResponseTypeString _ = " json"
177+ wrapResponseType = JSONResponse
178+
175179instance (Json. FromJSON a ) => Client (JSON a ) where
176180 -- note that we do not decode eagerly because it's often the case that the body
177181 -- cannot be decoded since web servers return invalid json on errors
178182 -- (e.g. "Internal server error" on a 500 rather than a json encoded error)
179- type RequestData (JSON a ) = GetResponse ( Json. SomeValue Immutable ) (Maybe (Either String a ))
183+ type RequestData (JSON a ) = GetResponse JSONResponse ( IO (Maybe (Either String a ) ))
180184 performRequest _p req (GetResponse f) = do
181185 resp <- Xhr. xhr =<< toXhrRequest req
182- f resp $ do
183- data_ <- Xhr. contents resp
184- return (Json. parseEither Json. parseJSON data_)
186+ f resp $ for (Xhr. contents resp) $ \ (JSONResponse data_) ->
187+ Json. runParser Json. parseJSON data_
185188
186189instance (Client next ) => Client (ExtraHeaders next ) where
187190 type RequestData (ExtraHeaders next ) = RequestData next
@@ -193,8 +196,10 @@ instance (Client next) => Client (NoCache next) where
193196
194197instance (Client next , Json. ToJSON a ) => Client (ReqBodyJSON a next ) where
195198 type RequestData (ReqBodyJSON a next ) = WithData a (RequestData next )
196- performRequest _p req (WithData x perf) = performRequest
197- (Proxy @ next ) req{reqData = Xhr. StringData (Json. encode (Json. toJSON x))} perf
199+ performRequest _p req (WithData x perf) = do
200+ s <- Json. toJSONString =<< Json. toJSON x
201+ performRequest
202+ (Proxy @ next ) req{reqData = Xhr. StringData s} perf
198203
199204instance (Client next ) => Client (WithIO next ) where
200205 type RequestData (WithIO next ) = RequestData next
0 commit comments