use bytes::Bytes;
use reqwest::{header::CONTENT_TYPE, Method};
use serde::{Deserialize, Serialize};
use super::Client;
use crate::{error::Result, Error};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Endpoint {
pub name: Option<String>,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UrlGroup {
pub created_at: u64,
pub updated_at: u64,
pub name: String,
pub endpoints: Vec<Endpoint>,
}
#[derive(Debug, Serialize)]
struct EndpointsPayload<'a> {
endpoints: &'a [Endpoint],
}
pub struct UrlGroupsApi<'a> {
pub(crate) client: &'a Client,
}
impl UrlGroupsApi<'_> {
pub async fn list(&self) -> Result<Vec<UrlGroup>> {
self.client
.http
.send_json(Method::GET, "v2/topics", &[], None, None)
.await
}
pub async fn get(&self, name: &str) -> Result<UrlGroup> {
self.client
.http
.send_json(Method::GET, &format!("v2/topics/{name}"), &[], None, None)
.await
}
pub async fn upsert_endpoints(&self, name: &str, endpoints: &[Endpoint]) -> Result<()> {
let body = Bytes::from(
serde_json::to_vec(&EndpointsPayload { endpoints }).map_err(Error::Serialize)?,
);
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/json"),
);
self.client
.http
.send_empty(
Method::POST,
&format!("v2/topics/{name}/endpoints"),
&[],
Some(headers),
Some(body),
)
.await
}
pub async fn remove_endpoints(&self, name: &str, endpoints: &[Endpoint]) -> Result<()> {
let body = Bytes::from(
serde_json::to_vec(&EndpointsPayload { endpoints }).map_err(Error::Serialize)?,
);
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/json"),
);
self.client
.http
.send_empty(
Method::DELETE,
&format!("v2/topics/{name}/endpoints"),
&[],
Some(headers),
Some(body),
)
.await
}
pub async fn delete(&self, name: &str) -> Result<()> {
self.client
.http
.send_empty(
Method::DELETE,
&format!("v2/topics/{name}"),
&[],
None,
None,
)
.await
}
}