init store from serde file

This commit is contained in:
David Westgate 2024-04-26 19:27:18 -07:00
parent 4da5c12c33
commit cbb470b33e
3 changed files with 18 additions and 9 deletions

View File

@ -8,5 +8,6 @@ edition = "2021"
[dependencies]
axum = "0.7.5"
serde = "1.0.198"
tokio = { version = "1.2", features = ["full"] }
serde_json = "1.0.116"
tokio = { version = "1.2", features = ["full", "derive"] }
warp = "0.3.7"

View File

@ -1,5 +1,6 @@
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
struct Store {
@ -9,9 +10,14 @@ struct Store {
impl Store {
fn new() -> Self {
Store {
questions: HashMap::new(),
questions: Self::init(),
}
}
fn init() -> HashMap<u8, Question> {
let file = include_str!("./questions.json");
serde_json::from_str(file).expect("can't read questions.json")
}
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)),
@ -46,7 +52,7 @@ impl Store {
}
}
}
#[derive(Clone)]
#[derive(Deserialize, Serialize, Clone)]
pub(crate) struct Question {
id: u8,
title: String,
@ -64,9 +70,3 @@ impl Question {
}
}
}
// impl IntoResponse for &Question {
// fn into_response(self) -> Response {
// (StatusCode::OK, Json(&self)).into_response()
// }
// }

8
src/questions.json Normal file
View File

@ -0,0 +1,8 @@
{
"1" : {
"id": "1",
"title": "How?",
"content": "Please help!",
"tags": ["general"]
}
}