Save votes to JSON as soon as they come in
For hopefully fewer cases of data loss if the program is killed.
This commit is contained in:
parent
40c6ed2c44
commit
5c1f7c98c1
1 changed files with 14 additions and 6 deletions
20
src/main.rs
20
src/main.rs
|
@ -23,6 +23,17 @@ struct AppState {
|
||||||
record: Arc<Mutex<VoteRecord>>,
|
record: Arc<Mutex<VoteRecord>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
fn save(&self) {
|
||||||
|
let st = self.record.lock().unwrap().to_owned();
|
||||||
|
serde_json::to_writer(
|
||||||
|
&std::fs::File::create("votes.json").unwrap(),
|
||||||
|
&st,
|
||||||
|
)
|
||||||
|
.expect("failed to write votes!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn view_votes(State(state): State<AppState>, Path(slug): Path<String>) -> Json<Page> {
|
async fn view_votes(State(state): State<AppState>, Path(slug): Path<String>) -> Json<Page> {
|
||||||
tracing::info!("Requesting votes for {slug}");
|
tracing::info!("Requesting votes for {slug}");
|
||||||
|
|
||||||
|
@ -54,6 +65,8 @@ async fn leaderboard_submit_score(State(state): State<AppState>, Path(slug): Pat
|
||||||
.pages
|
.pages
|
||||||
.push(Page { slug, votes: 1 });
|
.push(Page { slug, votes: 1 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
state.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
|
@ -85,10 +98,5 @@ async fn main() {
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let state_clone = initial_state.clone();
|
let state_clone = initial_state.clone();
|
||||||
let st = state_clone.record.lock().unwrap().to_owned();
|
state_clone.save();
|
||||||
serde_json::to_writer(
|
|
||||||
&std::fs::File::create("votes.json").unwrap(),
|
|
||||||
&st,
|
|
||||||
)
|
|
||||||
.expect("TODO: panic message");
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue