// src/api/notes.rs use axum::{ extract::{Query, State}, http::StatusCode, Json, }; use serde::{Deserialize, Serialize}; use std::sync::Arc; use sqlx::Row; use super::AppState; #[derive(Debug, Serialize, Deserialize)] pub struct NoteRecord { pub id: i64, pub bibcode: String, pub paragraph_index: i64, pub note_text: String, pub highlight_color: String, pub selected_text: String, pub created_at: String, } #[derive(Deserialize)] pub struct CreateNoteRequest { pub bibcode: String, pub paragraph_index: i64, pub note_text: Option, pub highlight_color: Option, pub selected_text: Option, } #[derive(Deserialize)] pub struct DeleteNoteParams { pub id: i64, } #[derive(Deserialize)] pub struct GetNotesParams { pub bibcode: String, } // 创建笔记 pub async fn create_note( State(state): State>, Json(req): Json, ) -> Result, (StatusCode, String)> { let note_text = req.note_text.unwrap_or_default(); let highlight_color = req.highlight_color.unwrap_or_else(|| "yellow".to_string()); let selected_text = req.selected_text.unwrap_or_default(); let row = sqlx::query( "INSERT INTO notes (bibcode, paragraph_index, note_text, highlight_color, selected_text) VALUES (?, ?, ?, ?, ?) RETURNING id, bibcode, paragraph_index, note_text, highlight_color, selected_text, created_at" ) .bind(&req.bibcode) .bind(req.paragraph_index) .bind(¬e_text) .bind(&highlight_color) .bind(&selected_text) .fetch_one(&state.db) .await .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("保存笔记失败: {}", e)))?; Ok(Json(NoteRecord { id: row.get(0), bibcode: row.get(1), paragraph_index: row.get(2), note_text: row.get(3), highlight_color: row.get(4), selected_text: row.get(5), created_at: row.get(6), })) } // 查询某篇文献的全部笔记 pub async fn get_notes( State(state): State>, Query(params): Query, ) -> Result>, (StatusCode, String)> { let rows = sqlx::query( "SELECT id, bibcode, paragraph_index, note_text, highlight_color, selected_text, created_at FROM notes WHERE bibcode = ? ORDER BY paragraph_index, created_at" ) .bind(¶ms.bibcode) .fetch_all(&state.db) .await .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("查询笔记失败: {}", e)))?; let notes: Vec = rows.iter().map(|r| NoteRecord { id: r.get(0), bibcode: r.get(1), paragraph_index: r.get(2), note_text: r.get(3), highlight_color: r.get(4), selected_text: r.get(5), created_at: r.get(6), }).collect(); Ok(Json(notes)) } // 删除指定 id 的笔记 pub async fn delete_note( State(state): State>, Query(params): Query, ) -> Result { sqlx::query("DELETE FROM notes WHERE id = ?") .bind(params.id) .execute(&state.db) .await .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("删除笔记失败: {}", e)))?; Ok(StatusCode::NO_CONTENT) }