|
1 | 1 | //! Aquatic responses are not serializable. These are the serializable wrappers.
|
2 | 2 | use std::net::{Ipv4Addr, Ipv6Addr};
|
3 | 3 |
|
| 4 | +use anyhow::Context; |
| 5 | +use aquatic_udp_protocol::Response::{self}; |
4 | 6 | use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse};
|
5 | 7 | use serde::Serialize;
|
6 | 8 |
|
| 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 | + |
7 | 44 | #[derive(Serialize)]
|
8 | 45 | pub struct ConnectResponseDto {
|
9 | 46 | transaction_id: i32,
|
|
0 commit comments