update rust lib with channel creation

This commit is contained in:
2026-01-10 10:59:19 +00:00
parent ebe8389cb3
commit 81022c4e21
2 changed files with 36 additions and 5 deletions

View File

@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
reqwest = { version = "0.11", features = ["json", "blocking"] }
reqwest = { version = "0.11", default-features = false, features = ["json", "blocking", "rustls-tls"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "1.0"

View File

@@ -41,6 +41,11 @@ struct SendMessagePayload {
content: String,
}
#[derive(Debug, Serialize)]
struct CreateChannelPayload {
name: String,
}
pub struct ChannelClient {
url: String,
client: Client,
@@ -87,6 +92,22 @@ impl ChannelClient {
Ok(channels.into_iter().find(|c| c.name == name))
}
/// Create a new channel
pub fn create_channel(&self, name: &str) -> Result<Channel, ChannelError> {
let payload = CreateChannelPayload {
name: name.to_string(),
};
let response = self
.client
.post(format!("{}/channels/", self.url))
.json(&payload)
.send()?
.error_for_status()?;
Ok(response.json()?)
}
/// Read messages from a channel by name
pub fn read_messages(
&self,
@@ -107,11 +128,16 @@ impl ChannelClient {
Ok(response.json()?)
}
/// Send a message to a channel by name
/// Send a message to a channel by name, creating the channel if it doesn't exist
pub fn send_message(&self, channel_name: &str, content: &str) -> Result<Message, ChannelError> {
let channel_id = self
.find_channel_id_by_name(channel_name)?
.ok_or_else(|| ChannelError::ChannelNotFound(channel_name.to_string()))?;
let channel_id = match self.find_channel_id_by_name(channel_name)? {
Some(id) => id,
None => {
// Channel doesn't exist, create it
let channel = self.create_channel(channel_name)?;
channel.id
}
};
let payload = SendMessagePayload {
content: content.to_string(),
@@ -143,6 +169,11 @@ pub fn read_channel(url: &str, token: &str, name: &str) -> Result<Option<Channel
create_client(url, token)?.read_channel(name)
}
/// Create a new channel
pub fn create_channel(url: &str, token: &str, name: &str) -> Result<Channel, ChannelError> {
create_client(url, token)?.create_channel(name)
}
/// Read messages from a channel by name
pub fn read_messages(
url: &str,