| 1 | |
|
| 2 | |
|
| 3 | | use super::{now_ms, Pool}; |
| 4 | | use sqlx::FromRow; |
| 5 | |
|
| 6 | | #[derive(Clone, Debug, FromRow)] |
| 7 | | pub struct Device { |
| 8 | | pub token_id: i64, |
| 9 | | pub account_id: i64, |
| 10 | | pub fcm_token: String, |
| 11 | | pub public_key: String, |
| 12 | | } |
| 13 | |
|
| 14 | |
|
| 15 | 3× | pub async fn register(pool: &Pool, token_id: i64, account_id: i64, fcm_token: &str, public_key: &str) -> sqlx::Result<()> { |
| 16 | 3× | let now = now_ms(); |
| 17 | 3× | sqlx::query( |
| 18 | 3× | "INSERT INTO push_devices (token_id, account_id, fcm_token, public_key, created_ms, updated_ms) VALUES ($1, $2, $3, $4, $5, $5) \ |
| 19 | 3× | ON CONFLICT (token_id) DO UPDATE SET fcm_token = excluded.fcm_token, public_key = excluded.public_key, updated_ms = excluded.updated_ms", |
| 20 | 3× | ) |
| 21 | 3× | .bind(token_id) |
| 22 | 3× | .bind(account_id) |
| 23 | 3× | .bind(fcm_token) |
| 24 | 3× | .bind(public_key) |
| 25 | 3× | .bind(now) |
| 26 | 3× | .execute(pool) |
| 27 | 3× | .await?; |
| 28 | 3× | Ok(()) |
| 29 | 3× | } |
| 30 | |
|
| 31 | 1× | pub async fn forget(pool: &Pool, token_id: i64) -> sqlx::Result<bool> { |
| 32 | 1× | Ok(sqlx::query("DELETE FROM push_devices WHERE token_id = $1").bind(token_id).execute(pool).await?.rows_affected() > 0) |
| 33 | 1× | } |
| 34 | |
|
| 35 | |
|
| 36 | 1× | pub async fn forget_fcm(pool: &Pool, fcm_token: &str) -> sqlx::Result<()> { |
| 37 | 1× | sqlx::query("DELETE FROM push_devices WHERE fcm_token = $1").bind(fcm_token).execute(pool).await?; |
| 38 | 1× | Ok(()) |
| 39 | 1× | } |
| 40 | |
|
| 41 | 5× | pub async fn of_account(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<Device>> { |
| 42 | 5× | sqlx::query_as("SELECT token_id, account_id, fcm_token, public_key FROM push_devices WHERE account_id = $1") |
| 43 | 5× | .bind(account_id) |
| 44 | 5× | .fetch_all(pool) |
| 45 | 5× | .await |
| 46 | 5× | } |