diff options
author | Lars Wirzenius <liw@liw.fi> | 2020-09-18 19:29:40 +0300 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2020-09-18 19:49:01 +0300 |
commit | aa3dd026c9a8c8407bccea0f1345f777afe0090c (patch) | |
tree | feebf7b8849698e36695b812993b17fca86e7298 /src/server.rs | |
parent | 77a5171b6541aceea6ddd3c4012522acdbd15f73 (diff) | |
download | obnam2-aa3dd026c9a8c8407bccea0f1345f777afe0090c.tar.gz |
feat: representations of responses for server operations
Diffstat (limited to 'src/server.rs')
-rw-r--r-- | src/server.rs | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..6b8a064 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,78 @@ +use crate::chunkid::ChunkId; +use crate::chunkmeta::ChunkMeta; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::default::Default; + +/// Result of creating a chunk. +#[derive(Debug, Serialize)] +pub struct Created { + id: ChunkId, +} + +impl Created { + pub fn new(id: ChunkId) -> Self { + Created { id } + } + + pub fn to_json(&self) -> String { + serde_json::to_string(&self).unwrap() + } +} + +/// Result of retrieving a chunk. +#[derive(Debug, Serialize)] +pub struct Fetched { + id: ChunkId, + meta: ChunkMeta, +} + +impl Fetched { + pub fn new(id: ChunkId, meta: ChunkMeta) -> Self { + Fetched { id, meta } + } +} + +/// Result of a search. +#[derive(Debug, Default, PartialEq, Deserialize, Serialize)] +pub struct SearchHits { + map: HashMap<String, ChunkMeta>, +} + +impl SearchHits { + pub fn insert(&mut self, id: ChunkId, meta: ChunkMeta) { + self.map.insert(format!("{}", id), meta); + } + + pub fn from_json(s: &str) -> anyhow::Result<Self> { + let map = serde_json::from_str(s)?; + Ok(SearchHits { map }) + } + + pub fn to_json(&self) -> String { + serde_json::to_string(&self.map).unwrap() + } +} + +#[cfg(test)] +mod test_search_hits { + use super::{ChunkMeta, SearchHits}; + + #[test] + fn no_search_hits() { + let hits = SearchHits::default(); + assert_eq!(hits.to_json(), "{}"); + } + + #[test] + fn one_search_hit() { + let id = "abc".parse().unwrap(); + let meta = ChunkMeta::new("123"); + let mut hits = SearchHits::default(); + hits.insert(id, meta); + eprintln!("hits: {:?}", hits); + let json = hits.to_json(); + let hits2 = SearchHits::from_json(&json).unwrap(); + assert_eq!(hits, hits2); + } +} |