summaryrefslogtreecommitdiff
path: root/haskell/src/SpaceTraders/APIClient/Errors.hs
blob: e4e55136713898f5e8e6612379caaa1b8a68fa0e (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
{-# LANGUAGE OverloadedStrings #-}

module SpaceTraders.APIClient.Errors
  ( APIError(..)
  , RateLimit(..)
  ) where

import Control.Exception
import Control.Monad
import Data.Aeson
import Data.Time
import qualified Data.Text as T

data APIError = APIError Int T.Text Value
              | APIRateLimit RateLimit
              deriving Show
instance Exception APIError
instance FromJSON APIError where
  parseJSON (Object o) = do
    e <- o .: "error"
    code <- e .: "code"
    d <- e .: "data"
    case code of
      429 -> APIRateLimit <$> parseJSON d
      _ -> APIError <$> pure code
                    <*> e .: "message"
                    <*> pure d
  parseJSON _ = mzero

data RateLimit = RateLimit { limitBurst :: Int
                           , limitPerSecond :: Int
                           , rateLimitType :: T.Text
                           , remaining :: Int
                           , reset :: UTCTime
                           , retryAfter :: Double
                           } deriving Show
instance FromJSON RateLimit where
  parseJSON (Object o) = do
    RateLimit <$> o .: "limitBurst"
              <*> o .: "limitPerSecond"
              <*> o .: "type"
              <*> o .: "remaining"
              <*> o .: "reset"
              <*> o .: "retryAfter"
  parseJSON _ = mzero