freechat/json-api/db/src/channels.rs
shockrah afdeef0a49 More warning removals and more db-lib result wrapping
This should be everything now
2021-03-30 23:00:50 -07:00

85 lines
2.8 KiB
Rust

use mysql_async::{params, Pool};
use mysql_async::prelude::Queryable;
use mysql_async::Error as SqlError;
use crate::{Channel, UBigInt, Integer};
use crate::Response;
use rand::RngCore;
pub const VOICE_CHANNEL: Integer = 1;
pub const TEXT_CHANNEL: Integer = 2;
pub const MAX_NAME_LEN: usize = 256;
pub const MAX_DESCRIPTION_LEN: usize = 2048;
impl Channel {
pub async fn filter(p: &Pool, kind: Integer) -> Result<Response<Self>, SqlError> {
//! @returns -> on success : Ok(Response::Set(Vec<Channel>))
//! @throw -> on sql fail : Err(SqlError)
if kind == VOICE_CHANNEL || kind ==TEXT_CHANNEL {
let mut conn = p.get_conn().await?;
let q = "SELECT id, name, description, kind FROM channels WHERE kind = :kind";
let params = params!{"kind" => kind};
let channels = conn.exec_map(q, params, |(id, name, description, kind)| {
Channel {
id, name, description, kind
}
}).await?;
Ok(Response::Set(channels))
} else {
return Ok(Response::RestrictedInput("Channel kind is invalid".into()));
}
}
pub async fn add(p: &Pool, name: &str, description: &str, kind: Integer)
-> Result<Response<Self>, SqlError> {
//! @returns on success -> Response::Row<Channel>
//! @returns on partial success -> Response::Empty
//! @returns on failure -> Response::Other
//! @returns on user failure -> Response::RestrictedInput(msg)
// bounds are literally [1, 2]
if kind == TEXT_CHANNEL || kind == VOICE_CHANNEL {
let mut conn = p.get_conn().await?;
let q = "INSERT INTO channels (id, name, description, kind) VALUES (:i, :n, :d, :k)";
let id = rand::rngs::OsRng.next_u64(); // generate id's randomly for channels
conn.exec_drop(q, params!{
"i" => id,
"n" => name,
"d" => description,
"k" => kind
}).await?;
Ok(Response::Row(Self {
id,
name: name.to_string(),
description: Some(description.to_string()),
kind
}))
}
else {
return Ok(Response::RestrictedInput(String::from("Invalid channel type")));
}
}
pub async fn delete(p: &Pool, id: UBigInt) -> Result<Response<Self>, SqlError> {
//! Deletes channel given UBigInt as the row key
//! @param p -> SqlPool
//! @param id -> UBigInt
//! @return on success -> Response::Success
//! @return on server failure -> Response::Other
let mut conn = p.get_conn().await?;
let q = "DELETE FROM channels WHERE id = :id";
conn.exec_drop(q, params!{"id" => id}).await?;
Ok(Response::Success)
}
}