source: src-tauri/src/commands/category.rs

main
Last change on this file was a4ca79c, checked in by Georgi Paunkov <paunkovgeorgi@…>, 5 days ago

Initial commit

  • Property mode set to 100644
File size: 2.3 KB
RevLine 
[a4ca79c]1use sqlx::PgPool;
2use tauri::State;
3
4use crate::commands::auth::{require_manager_session, ActiveSessions};
5use crate::models::category::Category;
6
7#[tauri::command]
8pub async fn get_categories(
9 pool: State<'_, PgPool>
10) -> Result<Vec<Category>, String> {
11 let categories = sqlx::query_as::<_, Category>(
12 "
13 SELECT
14 category_id,
15 name,
16 description
17 FROM category
18 WHERE active = true
19 ORDER BY name
20 "
21 )
22 .fetch_all(pool.inner())
23 .await
24 .map_err(|e| e.to_string())?;
25
26 Ok(categories)
27}
28
29#[tauri::command]
30pub async fn create_category(
31 token: String,
32 name: String,
33 description: String,
34 pool: State<'_, PgPool>,
35 sessions: State<'_, ActiveSessions>,
36) -> Result<(), String> {
37 require_manager_session(&token, sessions.inner()).await?;
38
39 if name.trim().is_empty() {
40 return Err("Името е задолжително".to_string());
41 }
42
43 sqlx::query(
44 "
45 INSERT INTO category (name, description)
46 VALUES ($1, $2)
47 "
48 )
49 .bind(name)
50 .bind(description)
51 .execute(pool.inner())
52 .await
53 .map_err(|e| e.to_string())?;
54
55 Ok(())
56}
57
58#[tauri::command]
59pub async fn update_category(
60 token: String,
61 category_id: i32,
62 name: String,
63 description: String,
64 pool: State<'_, PgPool>,
65 sessions: State<'_, ActiveSessions>,
66) -> Result<(), String> {
67 require_manager_session(&token, sessions.inner()).await?;
68
69 sqlx::query(
70 "
71 UPDATE category
72 SET name = $1,
73 description = $2
74 WHERE category_id = $3
75 "
76 )
77 .bind(name)
78 .bind(description)
79 .bind(category_id)
80 .execute(pool.inner())
81 .await
82 .map_err(|e| e.to_string())?;
83
84 Ok(())
85}
86
87#[tauri::command]
88pub async fn delete_category(
89 token: String,
90 category_id: i32,
91 pool: State<'_, PgPool>,
92 sessions: State<'_, ActiveSessions>,
93) -> Result<(), String> {
94 require_manager_session(&token, sessions.inner()).await?;
95
96 sqlx::query(
97 "
98 UPDATE category
99 SET active = false
100 WHERE category_id = $1
101 "
102 )
103 .bind(category_id)
104 .execute(pool.inner())
105 .await
106 .map_err(|e| e.to_string())?;
107
108 Ok(())
109}
Note: See TracBrowser for help on using the repository browser.