add question.rs draft

This commit is contained in:
David Westgate 2024-04-26 19:18:14 -07:00
parent c62357fd3e
commit 4da5c12c33

View File

@ -1,14 +1,61 @@
struct Question { use std::collections::HashMap;
id: QuestionId,
struct Store {
questions: HashMap<u8, Question>,
}
impl Store {
fn new() -> Self {
Store {
questions: HashMap::new(),
}
}
fn add(mut self, question: Question) -> Result<Question, String> {
match self.questions.get(&question.id) {
Some(_) => Err(format!("Question with id {} already exists", question.id)),
None => Ok(self
.questions
.insert(question.id.clone(), question)
.unwrap()),
}
}
fn remove(mut self, id: u8) -> Result<Question, String> {
match self.questions.remove(&id) {
Some(question) => Ok(question),
None => Err(format!("Question with id {} does not exist", id)),
}
}
fn fetch_one(self, id: u8) -> Result<Question, String> {
match self.questions.get(&id) {
Some(question) => Ok(question.clone()),
None => Err(format!("Question with id {} does not exist", id)),
}
}
fn fetch_all(self) -> Vec<Question> {
self.questions.values().cloned().collect()
}
fn update(mut self, question: Question) -> Result<Question, String> {
match self.questions.get(&question.id) {
Some(_) => Ok(self
.questions
.insert(question.id.clone(), question)
.unwrap()),
None => Err(format!("Question with id {} does not exists", question.id)),
}
}
}
#[derive(Clone)]
pub(crate) struct Question {
id: u8,
title: String, title: String,
content: String, content: String,
tags: Option<Vec<String>>, tags: Option<Vec<String>>,
} }
struct QuestionId(String); impl Question {
fn new(id: u8, title: String, content: String, tags: Option<Vec<String>>) -> Self {
impl Question{
fn new(id: QuestionId, title: String, content: String, tags: Option<Vec<String>>) -> Self {
Question { Question {
id, id,
title, title,
@ -18,8 +65,8 @@ impl Question{
} }
} }
impl IntoResponse for &Question { // impl IntoResponse for &Question {
fn into_response(self) -> Response { // fn into_response(self) -> Response {
(StatusCode::OK, Json(&self)).into_response() // (StatusCode::OK, Json(&self)).into_response()
} // }
} // }