1use super::OutputFormatter;
2use crate::dns::{DnsRecord, PropagationResult};
3use crate::lookup::LookupResult;
4use crate::rdap::RdapResponse;
5use crate::status::StatusResponse;
6use crate::whois::WhoisResponse;
7
8pub struct JsonFormatter {
9 pretty: bool,
10}
11
12impl Default for JsonFormatter {
13 fn default() -> Self {
14 Self::new()
15 }
16}
17
18impl JsonFormatter {
19 pub fn new() -> Self {
20 Self { pretty: true }
21 }
22
23 pub fn compact(mut self) -> Self {
24 self.pretty = false;
25 self
26 }
27
28 fn to_json<T: serde::Serialize + ?Sized>(&self, value: &T) -> String {
29 if self.pretty {
30 serde_json::to_string_pretty(value).unwrap_or_else(|e| format!("{{\"error\": \"{}\"}}", e))
31 } else {
32 serde_json::to_string(value).unwrap_or_else(|e| format!("{{\"error\": \"{}\"}}", e))
33 }
34 }
35}
36
37impl OutputFormatter for JsonFormatter {
38 fn format_whois(&self, response: &WhoisResponse) -> String {
39 self.to_json(response)
40 }
41
42 fn format_rdap(&self, response: &RdapResponse) -> String {
43 self.to_json(response)
44 }
45
46 fn format_dns(&self, records: &[DnsRecord]) -> String {
47 self.to_json(records)
48 }
49
50 fn format_propagation(&self, result: &PropagationResult) -> String {
51 self.to_json(result)
52 }
53
54 fn format_lookup(&self, result: &LookupResult) -> String {
55 self.to_json(result)
56 }
57
58 fn format_status(&self, response: &StatusResponse) -> String {
59 self.to_json(response)
60 }
61}