You have to change the code of your function to return a struct instead of a u32 value.
With the response you are looking for, the struct would be:
pub struct CustomResponse {
code: u32,
sum: u32,
}
In order to Serialize/Deserialize this struct for the RpcResponse you will have to add a library to do that.
Import it in your Cargo.toml file:
serde = "1.0.136"
serde_json = "1.0.85"
And include the decorator to your struct:
#[derive(serde::Deserialize, serde::Serialize)]
pub struct CustomResponse {
code: u32,
sum: u32,
}
The RPC's implementation has to be modified too for returning the new struct in the response.
Change the get_sum declaration to use the new struct.
#[rpc]
pub trait SumStorageApi<BlockHash> {
#[rpc(name = "sumStorage_getSum")]
fn get_sum(
&self,
at: Option<BlockHash>
) -> Result<CustomResponse>;
}
And finally change the implementation of the get_sum function from:
fn get_sum(
&self,
at: Option<<Block as BlockT>::Hash>
) -> Result<u32> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(||
// If the block hash is not supplied assume the best block.
self.client.info().best_hash
));
let runtime_api_result = api.get_sum(&at);
runtime_api_result.map_err(|e| RpcError {
code: ErrorCode::ServerError(9876), // No real reason for this value
message: "Something wrong".into(),
data: Some(format!("{:?}", e).into()),
})
}
To:
fn get_sum(
&self,
at: Option<<Block as BlockT>::Hash>
) -> Result<CustomResponse> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(||
// If the block hash is not supplied assume the best block.
self.client.info().best_hash
));
let runtime_api_result = api.get_sum(&at);
runtime_api_result.map_err(|e| RpcError {
code: ErrorCode::ServerError(9876), // No real reason for this value
message: "Something wrong".into(),
data: Some(format!("{:?}", e).into()),
});
Ok(CustomResponse{ code: 200, sum: value.unwrap()})
}
When query this RPC call you should get something like it now:
{
"jsonrpc": "2.0",
"result": {
"code": 200,
"sum": 18
},
"id": 3
}