Skip to content

Commit

Permalink
fix database connection not can't write
Browse files Browse the repository at this point in the history
  • Loading branch information
vazw committed May 26, 2024
1 parent 63a901b commit 038e0ad
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 74 deletions.
9 changes: 4 additions & 5 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ pub async fn get_username(
db: web::Data<Pool<Sqlite>>,
name: &str,
) -> std::io::Result<Option<UsersData>> {
let lowercase_name = name.to_lowercase();
let query = format!("SELECT * FROM users WHERE name='{lowercase_name}'");
let query = format!("SELECT * FROM users WHERE name='{name}'");
match sqlx::query_as::<_, UsersData>(&query)
.fetch_one(&**db)
.await
Expand All @@ -45,7 +44,7 @@ pub async fn verify(db: web::Data<Pool<Sqlite>>, payload: web::Query<Name>) -> i
match user {
Some(user) => {
let user_respon = format!("{{\"{}\":\"{}\"}}", user.name, user.pubkey);
let relay_respon = format!("{{\"{}\":{}}}", user.pubkey, "[\"wss://relay.siamstr.com\", \"wss://relay.notoshi.win\", \"wss://bostr.lecturify.net\"]");
let relay_respon = format!("{{\"{}\":{}}}", user.pubkey, "[\"wss://relay.siamstr.com\", \"wss://relay.notoshi.win\", \"wss://bostr.lecturify.net/?accurate=1\"]");
let nip46 = format!("{{\"{}\":{}}}", user.pubkey, "[\"wss://sign.siamstr.com\"]");
let respon: NostrUser = NostrUser {
names: serde_json::from_str(&user_respon).unwrap(),
Expand Down Expand Up @@ -95,10 +94,10 @@ pub async fn lnurl(db: web::Data<Pool<Sqlite>>, payload: web::Path<String>) -> i
}
}
} else {
HttpResponse::NotFound().json(
return HttpResponse::NotFound().json(
serde_json::from_str::<Value>("{{\"status\":400,\"message\":\"Error\"}")
.unwrap(),
)
);
}
}
None => HttpResponse::NotFound()
Expand Down
172 changes: 103 additions & 69 deletions src/app/core_api/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ use nostr_sdk::prelude::*;
#[cfg(feature = "ssr")]
use chrono::Local;
#[cfg(feature = "ssr")]
use sqlx::{Pool, Sqlite};
#[cfg(feature = "ssr")]
use uuid::Uuid;
#[cfg(feature = "ssr")]
pub const DB_URL: &str = "sqlite://db/database.db";
#[cfg(feature = "ssr")]
use sqlx::{Connection, FromRow, SqliteConnection, Row};
#[cfg(feature = "ssr")]
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
Ok(SqliteConnection::connect(DB_URL).await?)
}

#[cfg(feature = "ssr")]
#[derive(Debug, Clone, FromRow, Serialize, Deserialize, PartialEq, Eq)]
Expand Down Expand Up @@ -58,17 +56,23 @@ pub struct BoolRespons {

#[server]
pub async fn count_users(_count: i32) -> Result<CountsRespon, ServerFnError> {
let mut con = db().await.unwrap();
let query = "SELECT COUNT(*) FROM users";
let result = sqlx::query(query)
.fetch_one(&mut con)
.await;
match result {
Ok(user) => {
let num :i32=user.get(0);
Ok(CountsRespon { count: num })
if leptos::leptos_dom::is_server() {
use actix_web::web::Data;
use leptos_actix::*;
let con: Data<Pool<Sqlite>> = extract().await?;
let query = "SELECT COUNT(*) FROM users";
let result = sqlx::query(query)
.fetch_one(&**con)
.await;
match result {
Ok(user) => {
let num :i32=user.get(0);
Ok(CountsRespon { count: num })
}
Err(_) => Ok(CountsRespon { count: 0 }),
}
Err(_) => Ok(CountsRespon { count: 0 }),
} else {
Ok(CountsRespon { count: 0 })
}
}

Expand All @@ -82,40 +86,52 @@ pub async fn check_npub(public_key: String) -> Result<UserRespons, ServerFnError
} else {
hex_npub.clone_from(&public_key);
}
let mut con = db().await.unwrap();
let query = format!("SELECT * FROM users WHERE pubkey='{hex_npub}'");
let result = sqlx::query_as::<_, UsersData>(&query)
.fetch_one(&mut con)
.await;
match result {
Ok(user) => Ok(UserRespons {
user: Some(UsersDataResult {
id: user.id,
name: user.name,
pubkey: user.pubkey,
lightning_url: user.lightning_url,
created: user.created,
if leptos::leptos_dom::is_server() {
use actix_web::web::Data;
use leptos_actix::*;
let con: Data<Pool<Sqlite>> = extract().await?;
let query = format!("SELECT * FROM users WHERE pubkey='{hex_npub}'");
let result = sqlx::query_as::<_, UsersData>(&query)
.fetch_one(&**con)
.await;
match result {
Ok(user) => Ok(UserRespons {
user: Some(UsersDataResult {
id: user.id,
name: user.name,
pubkey: user.pubkey,
lightning_url: user.lightning_url,
created: user.created,
}),
}),
}),
Err(_) => Ok(UserRespons { user: None }),
Err(_) => Ok(UserRespons { user: None }),
}
} else {
Ok(UserRespons { user: None })
}
}

#[server]
pub async fn check_username(username: String) -> Result<BoolRespons, ServerFnError> {
let mut con = db().await.unwrap();
if username.is_empty() {
Ok(BoolRespons { status: 0 })
} else {
let username = username.to_lowercase();
let query = format!("SELECT * FROM users WHERE name='{username}'");
let result = sqlx::query_as::<_, UsersData>(&query)
.fetch_one(&mut con)
.await;
match result {
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
if leptos::leptos_dom::is_server() {
use actix_web::web::Data;
use leptos_actix::*;
if username.is_empty() {
Ok(BoolRespons { status: 0 })
} else {
let con: Data<Pool<Sqlite>> = extract().await?;
let username = username.to_lowercase();
let query = format!("SELECT * FROM users WHERE name='{username}'");
let result = sqlx::query_as::<_, UsersData>(&query)
.fetch_one(&**con)
.await;
match result {
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
}
}
} else {
Ok(BoolRespons { status: 0 })
}
}

Expand All @@ -128,18 +144,24 @@ pub async fn add_user(
let id = Uuid::new_v4().to_string();
let time_now = Local::now().to_rfc3339();
let lowercase_name = username.to_lowercase();
let mut con = db().await.unwrap();
match sqlx::query("INSERT INTO users (id,name,pubkey,lightning_url,created) VALUES (?,?,?,?,?)")
.bind(id)
.bind(lowercase_name)
.bind(pubkey)
.bind(lnurl)
.bind(time_now)
.execute(&mut con)
.await
{
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
if leptos::leptos_dom::is_server() {
use actix_web::web::Data;
use leptos_actix::*;
let con: Data<Pool<Sqlite>> = extract().await?;
match sqlx::query("INSERT INTO users (id,name,pubkey,lightning_url,created) VALUES (?,?,?,?,?)")
.bind(id)
.bind(lowercase_name)
.bind(pubkey)
.bind(lnurl)
.bind(time_now)
.execute(&**con)
.await
{
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
}
} else {
Ok(BoolRespons { status: 0 })
}
}

Expand All @@ -152,14 +174,20 @@ pub async fn edit_user(
) -> Result<BoolRespons, ServerFnError> {
let events : Event = Event::from_json(events).unwrap();
if events.verify().is_ok() && events.pubkey.to_string() == pubkey {
let mut con = db().await.unwrap();
let username = username.to_lowercase();
let query = format!(
"UPDATE users SET name='{username}', lightning_url='{lnurl}' WHERE pubkey='{pubkey}'"
);
match sqlx::query(&query).execute(&mut con).await {
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
if leptos::leptos_dom::is_server() {
use actix_web::web::Data;
use leptos_actix::*;
let con: Data<Pool<Sqlite>> = extract().await?;
let username = username.to_lowercase();
let query = format!(
"UPDATE users SET name='{username}', lightning_url='{lnurl}' WHERE pubkey='{pubkey}'"
);
match sqlx::query(&query).execute(&**con).await {
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
}
} else {
Ok(BoolRespons { status: 0 })
}
} else {
Ok(BoolRespons { status: 0 })
Expand All @@ -171,14 +199,20 @@ pub async fn edit_user(
pub async fn delete_user(pubkey: String, events: String) -> Result<BoolRespons, ServerFnError> {
let events : Event = Event::from_json(events).unwrap();
if events.pubkey.to_string() == pubkey && events.verify().is_ok() {
let mut con = db().await.unwrap();
match sqlx::query("DELETE FROM users WHERE pubkey=(?)")
.bind(pubkey)
.execute(&mut con)
.await
{
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
if leptos::leptos_dom::is_server() {
use actix_web::web::Data;
use leptos_actix::*;
let con: Data<Pool<Sqlite>> = extract().await?;
match sqlx::query("DELETE FROM users WHERE pubkey=(?)")
.bind(pubkey)
.execute(&**con)
.await
{
Ok(_user) => Ok(BoolRespons { status: 1 }),
Err(_) => Ok(BoolRespons { status: 0 }),
}
} else {
Ok(BoolRespons { status: 0 })
}
} else {
Ok(BoolRespons { status: 0 })
Expand Down

0 comments on commit 038e0ad

Please sign in to comment.