Skip to content

Commit 625db48

Browse files
committed
refactor: [#670] new trait for printing responses in JSON format and enum for Dto wrapper
1 parent 4de7793 commit 625db48

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/console/clients/udp/responses.rs

+37
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,46 @@
11
//! Aquatic responses are not serializable. These are the serializable wrappers.
22
use std::net::{Ipv4Addr, Ipv6Addr};
33

4+
use anyhow::Context;
5+
use aquatic_udp_protocol::Response::{self};
46
use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse};
57
use serde::Serialize;
68

9+
pub trait DtoToJson {
10+
fn print_response(&self) -> anyhow::Result<()>
11+
where
12+
Self: Serialize,
13+
{
14+
let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?;
15+
println!("{pretty_json}");
16+
17+
Ok(())
18+
}
19+
}
20+
21+
#[derive(Serialize)]
22+
pub enum ResponseDto {
23+
Connect(ConnectResponseDto),
24+
AnnounceIpv4(AnnounceResponseDto),
25+
AnnounceIpv6(AnnounceResponseDto),
26+
Scrape(ScrapeResponseDto),
27+
Error(ErrorResponseDto),
28+
}
29+
30+
impl From<Response> for ResponseDto {
31+
fn from(response: Response) -> Self {
32+
match response {
33+
Response::Connect(response) => ResponseDto::Connect(ConnectResponseDto::from(response)),
34+
Response::AnnounceIpv4(response) => ResponseDto::AnnounceIpv4(AnnounceResponseDto::from(response)),
35+
Response::AnnounceIpv6(response) => ResponseDto::AnnounceIpv6(AnnounceResponseDto::from(response)),
36+
Response::Scrape(response) => ResponseDto::Scrape(ScrapeResponseDto::from(response)),
37+
Response::Error(response) => ResponseDto::Error(ErrorResponseDto::from(response)),
38+
}
39+
}
40+
}
41+
42+
impl DtoToJson for ResponseDto {}
43+
744
#[derive(Serialize)]
845
pub struct ConnectResponseDto {
946
transaction_id: i32,

0 commit comments

Comments
 (0)