Prevent overwriting existing documents.

This commit is contained in:
2025-05-03 08:40:51 -04:00
parent ea825c89eb
commit e7c7d9f270
4 changed files with 87 additions and 9 deletions

View File

@@ -52,6 +52,15 @@ impl Document {
fn add(&mut self, msg: Message) {
let name = msg.get_data("name").unwrap().to_string();
match self.data.get(&name) {
Some(_) => {
let mut reply = msg.reply(MsgType::Error);
reply.add_data("error_type", ErrorType::DocumentAlreadyExists);
self.queue.send(reply).unwrap();
return;
},
None => {},
}
let doc: Value = serde_json::from_str(&msg.get_data("doc").unwrap().to_string()).unwrap();
self.data
.insert(name, doc["template"].as_str().unwrap().to_string());
@@ -63,7 +72,7 @@ impl Document {
Some(doc) => doc.to_string(),
None => "root".to_string(),
};
let mut reply = match self.data.get(&name) {
let reply = match self.data.get(&name) {
Some(data) => {
let mut holder = msg.reply(MsgType::Document);
holder.add_data("doc", data.clone());
@@ -140,10 +149,9 @@ pub mod documents {
#[test]
fn root_always_exists() {
let (queue, rx) = setup_document();
let name = format!("name-{}", Uuid::new_v4());
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("name", "root");
queue.send(msg);
queue.send(msg).unwrap();
let reply = rx.recv_timeout(TIMEOUT).unwrap();
match reply.get_msg_type() {
MsgType::Document => {}
@@ -191,4 +199,43 @@ pub mod documents {
}
assert_eq!(reply2.get_data("doc").unwrap().to_string(), content);
}
#[test]
fn add_does_not_overwrite_existing() {
let (queue, rx) = setup_document();
let mut holder = Message::new(MsgType::DocumentRequest);
holder.add_data("name", "root");
holder.add_data("action", ActionType::Get);
queue.send(holder.clone()).unwrap();
let binding = rx.recv_timeout(TIMEOUT).unwrap();
let expected = binding.get_data("doc").unwrap();
let input = json!({
"template": format!("content-{}", Uuid::new_v4())
});
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("name", "root");
msg.add_data("action", ActionType::Add);
msg.add_data("doc", input.to_string());
queue.send(msg.clone()).unwrap();
let reply = rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(reply.get_id(), msg.get_id());
match reply.get_msg_type() {
MsgType::Error=> {},
_ => unreachable!(
"got '{:?}': should have received document",
reply.get_msg_type()
),
}
match reply.get_data("error_type") {
Some(err) => match err.to_error_type().unwrap() {
ErrorType::DocumentAlreadyExists => {}
_ => unreachable!("got {:?}: should have been document not found'", err),
},
None => unreachable!("should contain error type"),
}
queue.send(holder).unwrap();
let binding = rx.recv_timeout(TIMEOUT).unwrap();
let result = binding.get_data("doc").unwrap();
assert_eq!(result.to_string(), expected.to_string());
}
}