json.rs
1 use std::collections::BTreeMap; 2 3 use serde_json::{json, Value}; 4 5 use radicle::cob; 6 use radicle::identity; 7 use radicle::node::AliasStore; 8 9 pub(crate) mod cobs; 10 pub(crate) mod commit; 11 pub(crate) mod diff; 12 pub(crate) mod thread; 13 14 /// Returns JSON for a `reaction`. 15 pub fn reactions( 16 reactions: BTreeMap<&cob::Reaction, Vec<&cob::ActorId>>, 17 location: Option<&cob::CodeLocation>, 18 aliases: &impl AliasStore, 19 ) -> Vec<Value> { 20 reactions 21 .into_iter() 22 .map(|(emoji, authors)| { 23 let authors = authors 24 .into_iter() 25 .map(|a| Author::new(&a.into()).as_json(aliases)) 26 .collect::<Vec<_>>(); 27 28 location.map_or( 29 json!({ 30 "emoji": emoji, 31 "authors": authors, 32 }), 33 |loc| { 34 json!({ 35 "location": diff::CodeLocation::new(loc).as_json(), 36 "emoji": emoji, 37 "authors": authors, 38 }) 39 }, 40 ) 41 }) 42 .collect::<Vec<_>>() 43 } 44 45 /// Returns JSON for an `Edit`. 46 pub fn embeds(embeds: &[cob::Embed<cob::Uri>]) -> Vec<Value> { 47 embeds 48 .iter() 49 .map(|e| { 50 json!({ 51 "name": e.name, 52 "content": e.content, 53 }) 54 }) 55 .collect::<Vec<_>>() 56 } 57 58 /// Returns JSON for an `Edit`. 59 pub fn edit(edit: &cob::thread::Edit, aliases: &impl AliasStore) -> Value { 60 json!({ 61 "author": Author::new(&edit.author.into()).as_json(aliases), 62 "body": edit.body, 63 "timestamp": edit.timestamp.as_secs(), 64 "embeds": embeds(&edit.embeds) 65 }) 66 } 67 68 pub(crate) struct Author<'a>(&'a identity::Did); 69 70 impl<'a> Author<'a> { 71 pub fn new(did: &'a identity::Did) -> Self { 72 Self(did) 73 } 74 75 pub fn as_json(&self, aliases: &impl AliasStore) -> Value { 76 aliases.alias(self.0).map_or( 77 json!({ "id": self.0 }), 78 |alias| json!({ "id": self.0, "alias": alias, }), 79 ) 80 } 81 }