JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Fixed imports!

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨ef0e853

⁨giterated-models/src/message.rs⁩ - ⁨1890⁩ bytes
Raw
1 use serde::Serialize;
2
3 use crate::{
4 object::{AnyObject, GiteratedObject},
5 operation::{AnyOperation, GiteratedOperation},
6 };
7 use std::fmt::Debug;
8
9 #[derive(Serialize)]
10 #[serde(bound(deserialize = "O: GiteratedObject, V: GiteratedOperation<O>"))]
11 pub struct GiteratedMessage<O: GiteratedObject, V: GiteratedOperation<O>> {
12 #[serde(with = "string")]
13 pub object: O,
14 pub operation: String,
15 pub payload: V,
16 }
17
18 mod string {
19 use std::fmt::Display;
20 use std::str::FromStr;
21
22 use serde::{de, Deserialize, Deserializer, Serializer};
23
24 pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
25 where
26 T: Display,
27 S: Serializer,
28 {
29 serializer.collect_str(value)
30 }
31
32 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
33 where
34 T: FromStr,
35 T::Err: Display,
36 D: Deserializer<'de>,
37 {
38 String::deserialize(deserializer)?
39 .parse()
40 .map_err(de::Error::custom)
41 }
42 }
43
44 impl GiteratedMessage<AnyObject, AnyOperation> {
45 pub fn try_into<O: GiteratedObject, V: GiteratedOperation<O>>(
46 &self,
47 ) -> Result<GiteratedMessage<O, V>, ()> {
48 let object = O::from_object_str(&self.object.0).map_err(|_| ())?;
49 let payload = serde_json::from_value::<V>(self.payload.0.clone()).map_err(|_| ())?;
50
51 Ok(GiteratedMessage {
52 object,
53 operation: self.operation.clone(),
54 payload,
55 })
56 }
57 }
58
59 impl<V: GiteratedOperation<O> + Debug, O: GiteratedObject + Debug> Debug
60 for GiteratedMessage<O, V>
61 {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 f.debug_struct("GiteratedMessage")
64 .field("object", &self.object)
65 .field("operation", &self.operation)
66 .field("payload", &self.payload)
67 .finish()
68 }
69 }
70