summaryrefslogtreecommitdiff
path: root/haskell/src/SpaceTraders/APIClient/Client.hs
blob: e4744aa33e4cdc5b7aa0e3f5ab13a14e29a7814a (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
64
65
66
67
68
69
{-# LANGUAGE OverloadedStrings #-}

module SpaceTraders.APIClient.Client
  ( APIError(..)
  , APIMessage(..)
  , defaultReq
  , fromJSONValue
  , send
  , tokenReq
  ) where

import Control.Exception
import Control.Monad
import Data.Aeson
import Data.Aeson.Types
import qualified Data.Text as T
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

data APIMessage = APIMessage { data_ :: Value } deriving (Show)
instance FromJSON APIMessage where
  parseJSON (Object o) = APIMessage <$> o .: "data"
  parseJSON _ = mzero

defaultReq :: Request
defaultReq = setRequestHost "api.spacetraders.io"
           $ setRequestPort 443
           $ setRequestSecure True
           $ setRequestHeader "Content-Type" ["application/json"]
           $ defaultRequest

tokenReq :: T.Text -> Request
tokenReq token = setRequestHeader "Authorization" [T.encodeUtf8 $ "Bearer " <> token]
               $ defaultReq

fromJSONValue :: FromJSON a => Value -> Either String a
fromJSONValue = parseEither parseJSON

send :: FromJSON a => Request -> IO (Either APIError a)
send request = do
  response <- httpLbs request
  let status = statusCode $ getResponseStatus response
      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]}
      Right r -> case fromJSONValue (data_ r) of
        Left e -> return $ Left APIError{apiErrorCode = -1001, apiErrorMessage = 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

--handleAPIError :: SomeException -> IO (Maybe RegisterMessage)
--handleAPIError e = do
--  print e
--  return Nothing