63 lines
1.3 KiB
Rust
63 lines
1.3 KiB
Rust
|
|
use sqlx::SqlitePool;
|
||
|
|
use crate::{
|
||
|
|
Result,
|
||
|
|
Feed
|
||
|
|
};
|
||
|
|
|
||
|
|
pub struct UserId(pub i64);
|
||
|
|
impl From<i64> for UserId { fn from(id: i64) -> Self { UserId(id) } }
|
||
|
|
impl From<UserId> for i64 { fn from(id: UserId) -> Self { id.0 } }
|
||
|
|
|
||
|
|
pub struct User {
|
||
|
|
pub id: UserId,
|
||
|
|
pub name: String,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl User {
|
||
|
|
pub async fn get_all(pool: &SqlitePool) -> Result<Vec<Self>> {
|
||
|
|
let users = sqlx::query_as!(
|
||
|
|
User,
|
||
|
|
"SELECT id, name FROM users"
|
||
|
|
).fetch_all(pool).await?;
|
||
|
|
|
||
|
|
Ok(users)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn create(pool: &SqlitePool, name: &str) -> Result<Self> {
|
||
|
|
let result = sqlx::query!(
|
||
|
|
"INSERT INTO users (name)
|
||
|
|
VALUES (?)
|
||
|
|
RETURNING id, name",
|
||
|
|
name
|
||
|
|
).fetch_one(pool).await?;
|
||
|
|
|
||
|
|
Ok(Self {
|
||
|
|
id: UserId(result.id),
|
||
|
|
name: result.name,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn update_name(
|
||
|
|
pool: &SqlitePool, id: UserId, new_name: &str
|
||
|
|
) -> Result<()> {
|
||
|
|
sqlx::query!(
|
||
|
|
"UPDATE users SET name = ? WHERE id = ?",
|
||
|
|
new_name, id.0
|
||
|
|
).execute(pool).await?;
|
||
|
|
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn get_feeds(pool: &SqlitePool, id: UserId) -> Result<Vec<Feed>> {
|
||
|
|
let feeds = sqlx::query_as!(
|
||
|
|
Feed,
|
||
|
|
"SELECT id FROM feeds WHERE user_id = ?",
|
||
|
|
id.0
|
||
|
|
).fetch_all(pool).await?;
|
||
|
|
|
||
|
|
Ok(feeds)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn name(&self) -> &str { &self.name }
|
||
|
|
}
|