aboutsummaryrefslogtreecommitdiffstats
path: root/backend/lib/ACMS/API/Fetch.hs
blob: 84330b18108dd0f13d1607bbc66d69ca097d919f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
{-# LANGUAGE OverloadedStrings #-}

module ACMS.API.Fetch
  ( APIMonad(fetch),
#ifndef ghcjs_HOST_OS
    Network.HTTP.Simple.Request,
    Network.HTTP.Simple.setRequestMethod,
    Network.HTTP.Simple.setRequestBodyLBS,
#else
    JavaScript.Web.XMLHttpRequest.Request,
    setRequestMethod,
    setRequestBodyLBS,
#endif
  )
where

#ifndef ghcjs_HOST_OS
import Network.HTTP.Simple
#else
import Data.ByteString.Lazy.UTF8 qualified as LB
import Data.Maybe
import Data.String
import JavaScript.Web.XMLHttpRequest
import Miso.String qualified as J
import Data.ByteString qualified as B
#endif
import Control.Monad.Catch (MonadThrow)
import Data.ByteString.Lazy.Char8 qualified as LB
import Miso (JSM)

class (MonadThrow m) => APIMonad m where
  fetch :: Request -> m LB.ByteString

instance APIMonad JSM where
  fetch req = LB.fromStrict . getResponseBody <$> httpBS req

#ifdef ghcjs_HOST_OS
httpBS :: Request -> JSM (Response B.ByteString)
httpBS req = xhrByteString req

instance IsString Request where
  fromString uri =
    Request
      { reqMethod = GET,
        reqURI = J.pack uri,
        reqLogin = Nothing,
        reqHeaders = [],
        reqWithCredentials = False,
        reqData = NoData
      }

setRequestMethod :: B.ByteString -> Request -> Request
setRequestMethod "POST" req = req {reqMethod = POST}

setRequestBodyLBS :: LB.ByteString -> Request -> Request
setRequestBodyLBS body req = req {reqData = StringData (J.pack (LB.toString body))}

getResponseBody :: Response B.ByteString -> B.ByteString
getResponseBody = fromMaybe "" . contents
#else
instance APIMonad IO where
  fetch req = LB.fromStrict . getResponseBody <$> httpBS req
#endif