init store from serde file
This commit is contained in:
parent
4da5c12c33
commit
cbb470b33e
@ -8,5 +8,6 @@ edition = "2021"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
axum = "0.7.5"
|
axum = "0.7.5"
|
||||||
serde = "1.0.198"
|
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"
|
warp = "0.3.7"
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
||||||
struct Store {
|
struct Store {
|
||||||
@ -9,9 +10,14 @@ struct Store {
|
|||||||
impl Store {
|
impl Store {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
Store {
|
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> {
|
fn add(mut self, question: Question) -> Result<Question, String> {
|
||||||
match self.questions.get(&question.id) {
|
match self.questions.get(&question.id) {
|
||||||
Some(_) => Err(format!("Question with id {} already exists", 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 {
|
pub(crate) struct Question {
|
||||||
id: u8,
|
id: u8,
|
||||||
title: String,
|
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
8
src/questions.json
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"1" : {
|
||||||
|
"id": "1",
|
||||||
|
"title": "How?",
|
||||||
|
"content": "Please help!",
|
||||||
|
"tags": ["general"]
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user