Skip to content

Commit

Permalink
feat: ✨ many update
Browse files Browse the repository at this point in the history
  • Loading branch information
dfrnoch committed Oct 31, 2023
1 parent ce24039 commit 58de4c4
Show file tree
Hide file tree
Showing 8 changed files with 956 additions and 726 deletions.
1,513 changes: 823 additions & 690 deletions src-tauri/Cargo.lock

Large diffs are not rendered by default.

12 changes: 8 additions & 4 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ members = ["prisma-cli"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[build-dependencies]
tauri-build = { version = "2.0.0-alpha.10", features = [] }
tauri-build = { version = "2.0.0-alpha.11", features = [] }

[dependencies]
tauri = { version = "2.0.0-alpha.16", features = ["macos-private-api"] }
tauri = { version = "2.0.0-alpha.17", features = ["macos-private-api"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
prisma-client-rust = { git = "https://github.com/Brendonovich/prisma-client-rust", tag = "0.6.9", features = [
"sqlite",
"migrations",
"mocking",
] }
], default-features = false }
tokio = { version = "1.33.0", features = ["macros"] }
window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy", branch = "dev" }
tauri-plugin-single-instance = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
Expand All @@ -33,10 +33,14 @@ tauri-plugin-dialog = { git = "https://github.com/tauri-apps/plugins-workspace",
tauri-plugin-http = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-fs = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-clipboard-manager = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-app = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-process = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-os = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-store = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
pretty_env_logger = "0.5.0"
log = "0.4"
thiserror = "1.0.50"
platform-dirs = "0.3.0"
anyhow = "1.0.75"
# tauri-specta = { version = "=2.0.0-rc.2", features = ["typescript"] }
# specta = "=2.0.0-rc.5"

Expand Down
4 changes: 3 additions & 1 deletion src-tauri/prisma-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ version = "0.0.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
prisma-client-rust-cli = { git = "https://github.com/Brendonovich/prisma-client-rust", tag = "0.6.8" }
prisma-client-rust-cli = { git = "https://github.com/Brendonovich/prisma-client-rust", features = [
"migrations",
], tag = "0.6.8" }
2 changes: 1 addition & 1 deletion src-tauri/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ datasource db {

generator client {
provider = "cargo prisma"
output = "../src/db.rs"
output = "../src/prisma.rs"
module_path = "crate::db"
}

Expand Down
32 changes: 32 additions & 0 deletions src-tauri/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use prisma_client_rust::migrations::DbPushError;
use serde::{Serialize, Serializer};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum CoreError {
#[error("Prisma New Client Error")]
PrismaNewClientError(#[from] prisma_client_rust::NewClientError),

#[error("Prisma Query Error")]
PrismaQueryError(#[from] prisma_client_rust::QueryError),

#[error("Tokio IO Error")]
TokioError(#[from] tokio::io::Error),

#[error("Tokio Join Error")]
TokioJoinError(#[from] tokio::task::JoinError),

#[error("Db Push Error")]
DbPushError(#[from] DbPushError),
}

impl Serialize for CoreError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}

pub type CommandResult<T, E = CoreError> = anyhow::Result<T, E>;
75 changes: 45 additions & 30 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,15 @@ extern crate objc;
mod window_ext;

#[allow(warnings, unused)]
mod db;
mod prisma;

use db::*;
mod error;
mod migrator;
mod util;

use error::{CommandResult, CoreError};
use migrator::new_client;
use prisma::*;
use prisma_client_rust::QueryError;
use serde::Deserialize;
use std::sync::Arc;
Expand All @@ -24,9 +30,6 @@ use window_vibrancy::apply_mica;
#[cfg(target_os = "macos")]
use window_vibrancy::apply_vibrancy;

// use tauri_specta::ts;
// use specta::{collect_types, Type};

#[derive(Clone, serde::Serialize)]
struct Payload {
args: Vec<String>,
Expand All @@ -37,22 +40,40 @@ type DbState<'a> = State<'a, Arc<PrismaClient>>;

// #[specta::specta]
#[tauri::command]
async fn check_db(db: DbState<'_>) -> Result<bool, ()> {
db.company()
.count(vec![])
.exec()
.await
.map_err(|_| ())
.map(|x| x > 0)
async fn check_db(client: DbState<'_>) -> CommandResult<i16> {
let company_count = client.company().count(vec![]).exec().await;

match company_count {
Ok(_) => {
// Query succeeded, return 200
Ok(200)
}
Err(_) => {
// Query failed, return 400
Ok(400)
}
}
}

#[tauri::command]
async fn migrate_and_populate(client: DbState<'_>) -> CommandResult<()> {
#[cfg(debug_assertions)]
client._db_push().await?;

#[cfg(not(debug_assertions))]
client._migrate_deploy().unwrap();

Ok(())
}

// #[specta::specta]
#[tauri::command]
async fn get_company(
db: DbState<'_>,
client: DbState<'_>,
id: Option<i32>,
) -> Result<Option<company::Data>, QueryError> {
db.company()
client
.company()
.find_first(vec![company::id::equals(id.unwrap_or(1))])
.exec()
.await
Expand All @@ -65,22 +86,21 @@ struct CreateCompanyData {

// #[specta::specta]
#[tauri::command]
async fn create_post(db: DbState<'_>, data: CreateCompanyData) -> Result<test::Data, ()> {
db.test()
async fn create_post(client: DbState<'_>, data: CreateCompanyData) -> Result<test::Data, ()> {
client
.test()
.create(data.name, vec![])
.exec()
.await
.map_err(|_| ())
}

#[tauri::command]
fn get_theme(window: tauri::Window) -> Theme {
window.theme().unwrap_or(Theme::Light)
}

#[tokio::main]
async fn main() {
let db = PrismaClient::_builder().build().await.unwrap();
std::env::set_var("RUST_LOG", "debug");
pretty_env_logger::init();

let client = new_client().await.unwrap();

// #[cfg(debug_assertions)]
// ts::export(
Expand All @@ -89,26 +109,21 @@ async fn main() {
// )
// .unwrap();

//TODO: enable only in release mode
// #[cfg(debug_assertions)]
// db.db_push().await.unwrap();

tauri::Builder::default()
.plugin(tauri_plugin_autostart::init(
MacosLauncher::LaunchAgent,
Some(vec!["--flag1", "--flag2"]),
))
.plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
println!("{}, {argv:?}, {cwd}", app.package_info().name);
app.emit_all("single-instance", Payload { args: argv, cwd })
app.emit("single-instance", Payload { args: argv, cwd })
.unwrap();
}))
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_app::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_store::Builder::default().build())
Expand All @@ -129,10 +144,10 @@ async fn main() {
.invoke_handler(tauri::generate_handler![
check_db,
get_company,
migrate_and_populate,
create_post,
get_theme
])
.manage(Arc::new(db))
.manage(Arc::new(client))
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
25 changes: 25 additions & 0 deletions src-tauri/src/migrator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use log::info;

use crate::{
error::CoreError,
prisma::{_prisma::PrismaClient, new_client_with_url},
util::get_app_dir,
};

pub async fn new_client() -> Result<PrismaClient, CoreError> {
let appdata_url = get_app_dir().join("app.db");

log::info!("Connecting to database at {}", appdata_url.display());

tokio::fs::create_dir_all(appdata_url.parent().unwrap()).await?;

if !appdata_url.exists() {
tokio::fs::File::create(appdata_url.clone()).await?;
info!("Created database at {}", appdata_url.display());
}

let client =
new_client_with_url(&("file:".to_string() + appdata_url.to_str().unwrap())).await?;

Ok(client)
}
19 changes: 19 additions & 0 deletions src-tauri/src/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use std::path::PathBuf;

/// Get the accoubting config directory.
/// This config directory has the following structure:
/// - data.db
/// - assets/ # All the images/videos/audios are stored here
/// - config.toml
pub fn get_app_dir() -> PathBuf {
// get app dir with /accounting. use std libary
let path = platform_dirs::AppDirs::new(Some("accounting"), true).unwrap();
let mut data_dir = path.data_dir;

// check if in dev mode
if cfg!(debug_assertions) {
data_dir.push("dev");
}

data_dir
}

0 comments on commit 58de4c4

Please sign in to comment.