]> www.average.org Git - pdns-pipe-nmc.git/blob - Data/JsonRpc.hs
wip JsonRpc response
[pdns-pipe-nmc.git] / Data / JsonRpc.hs
1 {-# LANGUAGE OverloadedStrings #-}
2
3 module JsonRpc  ( JsonRpcVersion(JsonRpcV1, JsonRpcV2)
4                 , JsonRpcRequest
5                 , JsonRpcNotification
6                 , JsonRpcError
7                 , JsonRpcResponse
8                 , parseJsonRpc
9                 ) where
10
11 import Data.ByteString.Lazy (ByteString)
12 import Control.Applicative ((<$>), (<*>), empty)
13 import Data.Either
14 import Data.Aeson
15
16 data JsonRpcVersion = JsonRpcV1 | JsonRpcV2
17         deriving (Show)
18
19 data JsonRpcRequest = JsonRpcRequest { jrpcVersion    :: JsonRpcVersion
20                                      , jrpcReqMethod  :: ByteString
21                                      , jrpcReqParams  :: [ByteString]
22                                      , jrpcReqId      :: ByteString
23                                      } deriving (Show)
24 instance ToJSON JsonRpcRequest where
25   toJSON (JsonRpcRequest version method params id) =
26     let l = [ "method" .= method, "params" .= params, "id" .= id ]
27     in case version of
28       JsonRpcV1 -> object l
29       JsonRpcV2 -> object $ ("jsonrpc" .= toJSON ("2.0" :: ByteString)):l
30
31 data JsonRpcNotification = JsonRpcNotification
32                                      { jrpcNtfVersion :: JsonRpcVersion
33                                      , jrpcNtfMethod  :: ByteString
34                                      , jrpcNtfParams  :: [ByteString]
35                                      } deriving (Show)
36 instance ToJSON JsonRpcNotification where
37   toJSON (JsonRpcNotification version method params) =
38     let l = [ "method" .= method, "params" .= params ]
39     in case version of
40       JsonRpcV1 -> object l
41       JsonRpcV2 -> object $ ("jsonrpc" .= toJSON ("2.0" :: ByteString)):l
42
43 data JsonRpcError = JsonRpcError { jrpcErrCode    :: Int
44                                  , jrpcErrMessage :: ByteString
45                                  , jrpcErrData    :: Maybe Value
46                                  } deriving (Show)
47
48 data JsonRpcResponse = JsonRpcResponse { jrpcRspResult :: Maybe Value
49                                        , jrpcRspError  :: JsonRpcError
50                                        , jrpcRspId     :: ByteString
51                                        } deriving (Show)
52
53 parseJsonRpc :: ByteString -> Either JsonRpcError JsonRpcResponse
54 parseJsonRpc _ = Left $ JsonRpcError (-1) "someerror" Nothing