Skip to content

Commit

Permalink
refactor: [#670] new trait for printing responses in JSON format and …
Browse files Browse the repository at this point in the history
…enum for Dto wrapper
  • Loading branch information
mario-nt committed Jun 3, 2024
1 parent 4de7793 commit 625db48
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/console/clients/udp/responses.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,46 @@
//! Aquatic responses are not serializable. These are the serializable wrappers.
use std::net::{Ipv4Addr, Ipv6Addr};

use anyhow::Context;
use aquatic_udp_protocol::Response::{self};
use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse};
use serde::Serialize;

pub trait DtoToJson {
fn print_response(&self) -> anyhow::Result<()>
where
Self: Serialize,
{
let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?;
println!("{pretty_json}");

Ok(())
}
}

#[derive(Serialize)]
pub enum ResponseDto {
Connect(ConnectResponseDto),
AnnounceIpv4(AnnounceResponseDto),
AnnounceIpv6(AnnounceResponseDto),
Scrape(ScrapeResponseDto),
Error(ErrorResponseDto),
}

impl From<Response> for ResponseDto {
fn from(response: Response) -> Self {
match response {
Response::Connect(response) => ResponseDto::Connect(ConnectResponseDto::from(response)),
Response::AnnounceIpv4(response) => ResponseDto::AnnounceIpv4(AnnounceResponseDto::from(response)),
Response::AnnounceIpv6(response) => ResponseDto::AnnounceIpv6(AnnounceResponseDto::from(response)),
Response::Scrape(response) => ResponseDto::Scrape(ScrapeResponseDto::from(response)),
Response::Error(response) => ResponseDto::Error(ErrorResponseDto::from(response)),
}
}
}

impl DtoToJson for ResponseDto {}

#[derive(Serialize)]
pub struct ConnectResponseDto {
transaction_id: i32,
Expand Down

0 comments on commit 625db48

Please sign in to comment.