Channel add behavior now also returns the same new channel that was just added

! We do this because in order to `get` the channel later we need its id.
Some clients will be updating channel data periodically so this helps to make smaller queries possible
This commit is contained in:
shockrah 2020-11-07 18:26:19 -08:00
parent 700da3695f
commit 4668ce7d0f

View File

@ -154,5 +154,40 @@ impl FromDB<Channel, Integer> for Channel {
}
impl Channel {
pub async fn add() {}
pub async fn add(p: &Pool, name: &str, desc: &str, kind: Integer) -> Response<Self> {
//! @returns on success -> Response::Row<Channel>
//! @returns on partial success -> Response::Empty
//! @returns on failure -> Response::Other
if let Ok(conn) = p.get_conn().await {
let q = "INSERT INTO channels (name, description, kind) VALUES (:n, :d, :k)";
let insert_result = conn.drop_exec(q, params!{
"n" => name,
"d" => desc,
"k" => kind
}).await;
if let Ok(conn) = insert_result {
// This is only kosher because names are enforced as unique by sql
let q = "SELECT id FROM channels WHERE name = :name";
let fetch_result : Result<(Conn, Option<UBigInt>), SqlError> =
conn.first_exec(q, params!{"name" => name}).await;
return match fetch_result {
Ok((_, id_opt)) => {
if let Some(id) = id_opt {
Response::Row(Channel {
id: id,
name: name.into(),
description: Some(desc.into()),
kind: kind
})
}
else { Response::Empty }
},
Err(_) => Response::Empty
};
}
return Response::Other("Could fetch new channel".into());
}
return Response::Other(no_conn!("db::channels::add"))
}
}