現在我們新增一個todo的檔案todo.rs
use rusqlite::{Connection, Result};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Todo {
pub id: String,
pub title: String,
pub date: String,
pub done: bool,
}
pub struct TodoApp {
pub conn: Connection,
}
impl TodoApp {
pub fn new()->Result<TodoApp>{
let db_path = "db.sqlite";
let conn = Connection::open(db_path)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS Todo (
id varchar(64) PRIMARY KEY,
title text NOT NULL,
date text NOT NULL,
done numeric DEFAULT 0
)",
[],
)?;
Ok(TodoApp { conn })
}
}
到main.rs新增:
mod todo;
use todo::{Todo, TodoApp};
並加入new方法到main()裡
fn main() {
let app = TodoApp::new().unwrap();
此時,我們測試一下pnpm tauri dev
我們發現出現warning,但我們能看到main.rs創建了db.sqlite
接著,我們打開並能看到table建起來了
接著回到todo.rs,新增獲取所有todo功能
impl TodoApp {
...
// Get All
pub fn get_todos(&self) -> Result<Vec<Todo>> {
let mut stmt = self.conn.prepare("SELECT * FROM Todo").unwrap();
let todos_iter = stmt.query_map([], |row| {
let done = row.get::<usize, i32>(3).unwrap() == 1;
Ok(Todo {
id: row.get(0)?,
title: row.get(1)?,
date: row.get(2)?,
done,
})
})?;
let mut todos: Vec<Todo> = Vec::new();
for todo in todos_iter {
todos.push(todo?);
}
Ok(todos)
}
}
回到main.rs
,接著將這個方法給加入到我們tauri中
...
use std::sync::Mutex;
use tauri::{CustomMenuItem, Menu, MenuItem, Submenu, Manager};
mod todo;
use todo::{Todo, TodoApp};
struct AppState {
app: Mutex<TodoApp>,
}
fn main() {
tauri::Builder::default()
...
.invoke_handler(tauri::generate_handler![
get_todos,
])
.manage(AppState {
app: Mutex::from(app),
})
...
}
#[tauri::command]
fn get_todos(state: tauri::State<AppState>) -> Vec<Todo> {
let app = state.app.lock().unwrap();
let todos = app.get_todos().unwrap();
todos
}
此時,我們能獲取所有todo的item了
測試方法,我們嘗試透過WebView Console
透過設置todo\src-tauri\tauri.conf.json
裡面的tauri.conf.json > build > withGlobalTauri
為true來將調用掛載到window.__TAURI__
對像上
打開我們的App,並按下F12,叫出devTool。並在我們的console輸入await __TAURI__.invoke("get_todos")
測試
我們發現能調用get_todos的方法了。明天接著把CRUD的功能給完善