domus

One damus client to rule them all
git clone git://jb55.com/domus
Log | Files | Refs | README

message.rs (1270B)


      1 use crate::{Event, Filter};
      2 use serde_json::json;
      3 
      4 /// Messages sent by clients, received by relays
      5 #[derive(Debug, Eq, PartialEq)]
      6 pub enum ClientMessage {
      7     Event {
      8         event: Event,
      9     },
     10     Req {
     11         sub_id: String,
     12         filters: Vec<Filter>,
     13     },
     14     Close {
     15         sub_id: String,
     16     },
     17 }
     18 
     19 impl ClientMessage {
     20     pub fn event(event: Event) -> Self {
     21         ClientMessage::Event { event }
     22     }
     23 
     24     pub fn req(sub_id: String, filters: Vec<Filter>) -> Self {
     25         ClientMessage::Req { sub_id, filters }
     26     }
     27 
     28     pub fn close(sub_id: String) -> Self {
     29         ClientMessage::Close { sub_id }
     30     }
     31 
     32     pub fn to_json(&self) -> String {
     33         match self {
     34             Self::Event { event } => json!(["EVENT", event]).to_string(),
     35             Self::Req { sub_id, filters } => {
     36                 let mut json = json!(["REQ", sub_id]);
     37                 let mut filters = json!(filters);
     38 
     39                 if let Some(json) = json.as_array_mut() {
     40                     if let Some(filters) = filters.as_array_mut() {
     41                         json.append(filters);
     42                     }
     43                 }
     44 
     45                 json.to_string()
     46             }
     47             Self::Close { sub_id } => json!(["CLOSE", sub_id]).to_string(),
     48         }
     49     }
     50 }