consume core in Tauri

This commit is contained in:
polv committed 2026-02-21 23:33:10 +07:00
1 parent 876b879a65
commit 59968e0d6c
14 files changed
+157 -75

No files matched your search

+1
View File
@@ -10,3 +10,4 @@ crate-type = ["cdylib", "rlib"]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
rusqlite = { version = "0.38.0", features = ["bundled", "unlock_notify"] }
thiserror = "2.0.18"
+6
View File
@@ -0,0 +1,6 @@
use crate::{error::CJDicError, service::AppService};
pub fn list_entries_json(service: &AppService) -> Result<String, CJDicError> {
let entries = service.list_entries()?;
Ok(serde_json::to_string(&entries)?)
}
+63
View File
@@ -0,0 +1,63 @@
use std::{path::Path, sync::Mutex};
use rusqlite::{Connection, Result};
use crate::models::Entry;
pub struct Database {
conn: Mutex<Connection>,
}
impl Database {
pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> {
let conn = Connection::open(path)?;
Ok(Self {
conn: Mutex::new(conn),
})
}
pub fn init(&self) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute_batch(
"
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY,
word TEXT NOT NULL,
definition TEXT NOT NULL
)",
)?;
Ok(())
}
pub fn insert_entry(&self, word: &str, definition: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO entries (word, definition) VALUES (?, ?)",
[word, definition],
)?;
Ok(())
}
pub fn fetch_all_entries(&self) -> Result<Vec<Entry>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, word, definition FROM entries")?;
let rows = stmt.query_map([], |row| {
Ok(Entry {
id: row.get(0)?,
word: row.get(1)?,
definition: row.get(2)?,
})
})?;
let mut entries = Vec::new();
for entry in rows {
entries.push(entry?);
}
Ok(entries)
}
}
+13
View File
@@ -0,0 +1,13 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum CJDicError {
#[error("Database error: {0}")]
Database(#[from] rusqlite::Error),
#[error("Serialization error: {0}")]
Serialization(#[from] serde_json::Error),
#[error("Not found")]
NotFound,
}
+8
View File
@@ -1,4 +1,12 @@
pub mod api;
pub mod db;
pub mod error;
pub mod models;
pub mod service;
pub use error::CJDicError;
pub use models::*;
pub use service::AppService;
pub fn add(left: u64, right: u64) -> u64 {
left + right
+24
View File
@@ -0,0 +1,24 @@
use std::path::Path;
use crate::{db::Database, error::CJDicError, models::Entry};
pub struct AppService {
db: Database,
}
impl AppService {
pub fn new<P: AsRef<Path>>(db_path: P) -> Result<Self, CJDicError> {
let db = Database::new(db_path)?;
db.init()?;
Ok(Self { db })
}
pub fn add_entry(&self, word: &str, definition: &str) -> Result<(), CJDicError> {
self.db.insert_entry(word, definition)?;
Ok(())
}
pub fn list_entries(&self) -> Result<Vec<Entry>, CJDicError> {
Ok(self.db.fetch_all_entries()?)
}
}