summaryrefslogtreecommitdiff
path: root/haskell/src/SpaceTraders/APIClient/Client.hs
diff options
context:
space:
mode:
Diffstat (limited to 'haskell/src/SpaceTraders/APIClient/Client.hs')
-rw-r--r--haskell/src/SpaceTraders/APIClient/Client.hs29
1 files changed, 15 insertions, 14 deletions
diff --git a/haskell/src/SpaceTraders/APIClient/Client.hs b/haskell/src/SpaceTraders/APIClient/Client.hs
index e4744aa..4e9e9d1 100644
--- a/haskell/src/SpaceTraders/APIClient/Client.hs
+++ b/haskell/src/SpaceTraders/APIClient/Client.hs
@@ -1,3 +1,4 @@
+{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
module SpaceTraders.APIClient.Client
@@ -9,6 +10,7 @@ module SpaceTraders.APIClient.Client
, tokenReq
) where
+import Control.Concurrent
import Control.Exception
import Control.Monad
import Data.Aeson
@@ -18,16 +20,7 @@ import qualified Data.Text.Encoding as T
import Network.HTTP.Simple
import Network.HTTP.Types.Status
-data APIError = APIError { apiErrorCode :: Int
- , apiErrorMessage :: T.Text
- } deriving Show
-instance Exception APIError
-instance FromJSON APIError where
- parseJSON (Object o) = do
- e <- o .: "error"
- APIError <$> e .: "code"
- <*> e .: "message"
- parseJSON _ = mzero
+import SpaceTraders.APIClient.Errors
data APIMessage = APIMessage { data_ :: Value } deriving (Show)
instance FromJSON APIMessage where
@@ -55,13 +48,21 @@ send request = do
body = getResponseBody response
if status >= 200 && status <= 299
then case eitherDecode body of
- Left e -> return $ Left APIError{apiErrorCode = -1000, apiErrorMessage = T.pack $ concat ["Error decoding JSON APIMessage: ", e]}
+ Left e -> return . Left $ APIError (-1000) Null (T.pack $ concat ["Error decoding JSON APIMessage: ", e])
Right r -> case fromJSONValue (data_ r) of
- Left e -> return $ Left APIError{apiErrorCode = -1001, apiErrorMessage = T.pack $ concat ["Error decoding JSON message contents: ", e]}
+ Left e -> return . Left $ APIError (-1001) Null (T.pack $ concat ["Error decoding JSON message contents: ", e])
Right m -> return $ Right m
else case eitherDecode body of
- Left e -> return $ Left APIError{apiErrorCode = -status, apiErrorMessage = T.pack $ concat ["Error decoding JSON APIError: ", e, ". Got HTTP body: ", show body]}
- Right e -> return $ Left e
+ Left e -> return . Left $ APIError (-status) Null (T.pack $ concat ["Error decoding JSON APIError: ", e, ". Got HTTP body: ", show body])
+ Right e -> case apiErrorCode e of
+ 429 -> do -- We are being rate limited
+ let d = apiErrorData e
+ w <- case fromJSONValue d of
+ Left _ -> throwIO e
+ Right e' -> return $ retryAfter e'
+ threadDelay (1_000_000 * (round w))
+ send request
+ _ -> return $ Left e
--handleAPIError :: SomeException -> IO (Maybe RegisterMessage)
--handleAPIError e = do