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