packages feed

sc2-lowlevel-0.1.0.0: src/Network/SC2/LowLevel/Requestable.hs

{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.SC2.LowLevel.Requestable
  ( Requestable(..)
  , extractResponse
  , extractResponseErr
  ) where

import Data.Proxy
import Data.Text
import Data.Maybe
import qualified Proto.S2clientprotocol.Sc2api as A
import qualified Proto.S2clientprotocol.Sc2api_Fields as A
import Data.Default.Class
import Control.Lens

class Requestable a where
  type ResponseOf a
  toRequest :: a -> A.Request
  fromResponse :: Proxy a -> A.Response -> Either Text (ResponseOf a)

instance Requestable A.Request where
  type ResponseOf A.Request = A.Response
  toRequest = id
  fromResponse _ = Right

extractResponse :: (A.Response -> Maybe a) -> A.Response -> Either Text a
extractResponse f r = maybe (Left ( (intercalate (pack "\n") (r ^. A.error)))) Right (f r)

extractResponseErr :: (A.Response -> Maybe a) -> (a -> Maybe b) -> (a -> Maybe Text) -> A.Response -> Either Text b
extractResponseErr f v e r =
  do x <- extractResponse f r
     case e x of
       Nothing  -> maybe (Left "error parsing payload") Right (v x)
       Just err -> Left (err)