1 {-# LANGUAGE OverloadedStrings #-}
4 ( JsonRpcVersion(JsonRpcV1, JsonRpcV2)
11 import Data.ByteString.Lazy (ByteString)
12 import Control.Applicative ((<$>), (<*>), empty)
16 data JsonRpcVersion = JsonRpcV1 | JsonRpcV2
19 data JsonRpcRequest = JsonRpcRequest { jrpcVersion :: JsonRpcVersion
20 , jrpcReqMethod :: ByteString
21 , jrpcReqParams :: [ByteString]
24 instance ToJSON JsonRpcRequest where
25 toJSON (JsonRpcRequest version method params id) =
26 let l = [ "method" .= method, "params" .= params, "id" .= id ]
29 JsonRpcV2 -> object $ ("jsonrpc" .= toJSON ("2.0" :: ByteString)):l
31 data JsonRpcNotification = JsonRpcNotification
32 { jrpcNtfVersion :: JsonRpcVersion
33 , jrpcNtfMethod :: ByteString
34 , jrpcNtfParams :: [ByteString]
36 instance ToJSON JsonRpcNotification where
37 toJSON (JsonRpcNotification version method params) =
38 let l = [ "method" .= method, "params" .= params ]
41 JsonRpcV2 -> object $ ("jsonrpc" .= toJSON ("2.0" :: ByteString)):l
43 data JsonRpcError = JsonRpcError { jrpcErrCode :: Int
44 , jrpcErrMessage :: ByteString
45 , jrpcErrData :: Maybe Value
47 instance FromJSON JsonRpcError where
48 parseJSON (Object o) = JsonRpcError
52 parseJSON x = return $ JsonRpcError
54 "Unparseable error object"
57 data JsonRpcResponse = JsonRpcResponse { jrpcRspResult :: Maybe Value
58 , jrpcRspError :: JsonRpcError
61 instance FromJSON JsonRpcResponse where
62 parseJSON (Object o) = JsonRpcResponse
66 parseJSON x = return $ JsonRpcResponse
70 "Unparseable response object"
75 parseJsonRpc :: (FromJSON a) => ByteString -> Either JsonRpcError a
76 parseJsonRpc s = case (decode s :: Maybe JsonRpcResponse) of
77 Just (JsonRpcResponse result error id) ->
79 Just v -> case fromJSON v of
81 Error s -> Left $ JsonRpcError (-32900) "Unparseable result" (Just v)
83 Nothing -> Left $ JsonRpcError (-32800) "Unparseable response" (Just (toJSON s))