|
| 1 | +{-# LANGUAGE OverloadedStrings, |
| 2 | + ExistentialQuantification #-} |
| 3 | + |
| 4 | +module Internal ( request |
| 5 | + , request2_0 |
| 6 | + , idRequest |
| 7 | + , successRsp |
| 8 | + , idSuccessRsp |
| 9 | + , errRsp |
| 10 | + , rpcErr |
| 11 | + , idErrRsp |
| 12 | + , fromJson |
| 13 | + , array |
| 14 | + , defaultId |
| 15 | + , errKey |
| 16 | + , dataKey |
| 17 | + , msgKey |
| 18 | + , resultKey |
| 19 | + , idKey |
| 20 | + , versionKey) where |
| 21 | + |
| 22 | +import qualified Data.Aeson as A |
| 23 | +import Data.Aeson ((.=)) |
| 24 | +import Data.Maybe (catMaybes) |
| 25 | +import qualified Data.Vector as V |
| 26 | +import Data.Text (Text) |
| 27 | +import Control.Applicative ((<$>)) |
| 28 | + |
| 29 | +fromJson :: A.FromJSON a => A.Value -> Maybe a |
| 30 | +fromJson v = case A.fromJSON v of |
| 31 | + A.Success x -> Just x |
| 32 | + _ -> Nothing |
| 33 | + |
| 34 | +array :: [A.Value] -> A.Value |
| 35 | +array = A.Array . V.fromList |
| 36 | + |
| 37 | +idRequest :: Text -> Maybe A.Value -> A.Value |
| 38 | +idRequest = request2_0 (Just defaultId) |
| 39 | + |
| 40 | +request2_0 :: Maybe A.Value -> Text -> Maybe A.Value -> A.Value |
| 41 | +request2_0 i = request (Just version) i . A.String |
| 42 | + |
| 43 | +request :: Maybe Text -> Maybe A.Value -> A.Value -> Maybe A.Value -> A.Value |
| 44 | +request ver i method args = A.object $ catMaybes [ Just $ "method" .= method |
| 45 | + , ("params" .=) <$> args |
| 46 | + , (idKey .=) <$> i |
| 47 | + , (versionKey .=) <$> ver ] |
| 48 | + |
| 49 | +idSuccessRsp :: A.Value -> A.Value |
| 50 | +idSuccessRsp = successRsp defaultId |
| 51 | + |
| 52 | +successRsp :: A.Value -> A.Value -> A.Value |
| 53 | +successRsp i = response i "result" |
| 54 | + |
| 55 | +idErrRsp :: Int -> A.Value |
| 56 | +idErrRsp = errRsp defaultId |
| 57 | + |
| 58 | +errRsp :: A.Value -> Int -> A.Value |
| 59 | +errRsp i code = response i errKey $ rpcErr Nothing code "" |
| 60 | + |
| 61 | +rpcErr :: Maybe A.Value -> Int -> Text -> A.Value |
| 62 | +rpcErr d code msg = A.object $ ["code" .= code, msgKey .= msg] ++ dataPair |
| 63 | + where dataPair = catMaybes [(dataKey .=) <$> d] |
| 64 | + |
| 65 | +response :: A.Value -> Text -> A.Value -> A.Value |
| 66 | +response i key result = A.object [idKey .= i, key .= result, versionKey .= version] |
| 67 | + |
| 68 | +defaultId :: A.Value |
| 69 | +defaultId = A.Number 3 |
| 70 | + |
| 71 | +versionKey :: Text |
| 72 | +versionKey = "jsonrpc" |
| 73 | + |
| 74 | +idKey :: Text |
| 75 | +idKey = "id" |
| 76 | + |
| 77 | +resultKey :: Text |
| 78 | +resultKey = "result" |
| 79 | + |
| 80 | +errKey :: Text |
| 81 | +errKey = "error" |
| 82 | + |
| 83 | +msgKey :: Text |
| 84 | +msgKey = "message" |
| 85 | + |
| 86 | +dataKey :: Text |
| 87 | +dataKey = "data" |
| 88 | + |
| 89 | +version :: Text |
| 90 | +version = "2.0" |
0 commit comments