0 | module HTTP.API.Client
  1 |
  2 | import Data.Linear.Traverse1
  3 | import HTTP.API.Client.FFI
  4 | import HTTP.I18n
  5 | import IO.Async.JS
  6 | import JSON.Simple
  7 | import JS
  8 | import Syntax.T1
  9 | import Web.Internal.Types
 10 |
 11 | import public HTTP.API.Client.Content
 12 | import public HTTP.API.Client.Header
 13 | import public HTTP.API.Client.Interface
 14 | import public HTTP.API.Client.Method
 15 | import public HTTP.API.Client.Path
 16 | import public HTTP.API.Client.Query
 17 | import public HTTP.API.Client.Request
 18 |
 19 | %default total
 20 |
 21 | ||| HTTP Errors
 22 | public export
 23 | data HTTPError : Type where
 24 |   Timeout      : HTTPError
 25 |   NetworkError : HTTPError
 26 |   DecError     : Bits16 -> DecodeErr -> HTTPError
 27 |   ReqError     : RequestErr -> HTTPError
 28 |
 29 | ||| Tries to convert an `HTTPErr` to an error of type `e`
 30 | ||| by decoding its `ReqError` constructor.
 31 | export %inline
 32 | toJSONErr : FromJSON e => HTTPError -> Maybe e
 33 | toJSONErr (ReqError x) = toJSONErr x
 34 | toJSONErr _            = Nothing
 35 |
 36 | ||| Tries to convert an `HTTPErr` to an error of type `e`
 37 | ||| and throws that in case the conversion succeeds. Otherwise,
 38 | ||| the original request error is rethrown.
 39 | export
 40 | decodeHTTPErr :
 41 |      (0 e : Type)
 42 |   -> {auto hr : Has HTTPError es}
 43 |   -> {auto ha : Has e es}
 44 |   -> {auto fj : FromJSON e}
 45 |   -> {auto me : MErr f}
 46 |   -> f es a
 47 |   -> f es a
 48 | decodeHTTPErr e act =
 49 |   catch HTTPError act >>= \case
 50 |     Right v => pure v
 51 |     Left x  => maybe (throw x) throw (toJSONErr @{fj} x)
 52 |
 53 | setFD : FormData -> (String,FDPart) -> IO1 ()
 54 | setFD fd (nm,FDBlob b)   t = appendBlob fd nm b t
 55 | setFD fd (nm,FDBytes b)  t = appendBytes fd nm b t
 56 | setFD fd (nm,FDFile f)   t = appendFile fd nm f t
 57 | setFD fd (nm,FDString s) t = appendTxt fd nm s t
 58 |
 59 | sendBody : XMLHttpRequest -> RequestBody -> IO1 ()
 60 | sendBody x None         t = send x t
 61 | sendBody x (Bytes mt b) t =
 62 |  let _   # t := setRequestHeader x Content_Type (encodeMediaType mt) t
 63 |      buf # t := ioToF1 (toBuffer b) t
 64 |   in sendBuffer x buf t
 65 | sendBody x (Blob mt b) t =
 66 |  let _   # t := setRequestHeader x Content_Type (encodeMediaType mt) t
 67 |   in sendBlob x b t
 68 | sendBody x (Str mt s)  t =
 69 |  let _   # t := setRequestHeader x Content_Type (encodeMediaType mt) t
 70 |   in sendTxt x s t
 71 | sendBody x (FD xs)     t =
 72 |  let fd  # t := newFD t
 73 |      _   # t := for1_ xs (setFD fd) t
 74 |   in sendFD x fd t
 75 |
 76 | data Decoder : Type -> Type where
 77 |   NoDec : Decoder ()
 78 |   Dec   : {0 f : Type} -> DecodeVia f t -> Decoder t
 79 |
 80 | adjHeader : Decoder t -> XMLHttpRequest -> IO1 ()
 81 | adjHeader NoDec   x t = () # t
 82 | adjHeader (Dec d) x t =
 83 |   setRequestHeader x Accept (encodeMediaType $ mediaType @{d}) t
 84 |
 85 | parameters {auto has : Has HTTPError es}
 86 |            {auto loc : HTTPLocal}
 87 |            (dec      : Decoder t)
 88 |            (cb       : Result es t -> IO1 ())
 89 |
 90 |   onerror : HTTPError -> Event -> IO1 ()
 91 |   onerror x _ = cb (Left $ inject x)
 92 |
 93 |   onsuccess : XMLHttpRequest -> IO1 ()
 94 |   onsuccess x =
 95 |     case dec of
 96 |       NoDec => cb (Right ())
 97 |       Dec d => T1.do
 98 |         st <- status x
 99 |         bs <- responseBytes x
100 |         cb (mapFst (inject . DecError st) $ decodeVia @{d} [] bs)
101 |
102 |   onload : XMLHttpRequest -> Event -> IO1 ()
103 |   onload x ev = T1.do
104 |     st <- status x
105 |     case st >= 200 && st < 300 of
106 |       False => T1.do
107 |         bs <- responseBytes x
108 |         let res := decodeVia {from = JSON, to = RequestErr} [] bs
109 |         cb (Left $ either (inject . DecError st) (inject . ReqError) res)
110 |       True  => onsuccess x
111 |
112 |   export
113 |   send1 : HTTPRequest -> IO1 (IO1 ())
114 |   send1 r = T1.do
115 |     x <- xmlhttpRequest
116 |     addEventListener (up x) "error" $ onerror NetworkError
117 |     addEventListener (up x) "load" $ onload x
118 |     addEventListener (up x) "timeout" $ onerror Timeout
119 |     opn x r.method r.uri
120 |
121 |     for1_ (kvList r.headers) $ setRequestHeaderP x
122 |     adjHeader dec x
123 |     sendBody x r.body
124 |
125 |     pure (abort x)
126 |
127 | parameters {auto has  : Has HTTPError es}
128 |            {auto loc  : HTTPLocal}
129 |            (endpoint  : HList ts)
130 |            {auto all  : All Receive ts}
131 |            {auto cons : HList (AllRecConstraints endpoint)}
132 |            (args      : HList (AllRecTypes endpoint))
133 |
134 |   export
135 |   sendEndpoint : Async JS es ()
136 |   sendEndpoint =
137 |     primAsync $ \cb =>
138 |       send1 NoDec cb (endpointRequest endpoint args emptyRequest)
139 |
140 |   export
141 |   requestEndpoint : (0 f,t : Type) -> (dec : DecodeVia f t) => Async JS es t
142 |   requestEndpoint f t =
143 |     primAsync $ \cb =>
144 |       send1 (Dec dec) cb (endpointRequest endpoint args emptyRequest)
145 |
146 |   export %inline
147 |   requestJSONEndpoint : (0 t : Type) -> DecodeVia JSON t => Async JS es t
148 |   requestJSONEndpoint = requestEndpoint JSON
149 |