Skip to main content

moq_api/
client.rs

1// SPDX-FileCopyrightText: 2024-2026 Cloudflare Inc., Luke Curley, Mike English and contributors
2// SPDX-FileCopyrightText: 2023-2024 Luke Curley and contributors
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use url::Url;
6
7use crate::{ApiError, Origin};
8
9#[derive(Clone)]
10pub struct Client {
11    // The address of the moq-api server
12    url: Url,
13
14    client: reqwest::Client,
15}
16
17impl Client {
18    pub fn new(url: Url) -> Self {
19        let client = reqwest::Client::new();
20        Self { url, client }
21    }
22
23    pub async fn get_origin(&self, namespace: &str) -> Result<Option<Origin>, ApiError> {
24        let url = self.url.join(&format!("origin/{namespace}"))?;
25        let resp = self.client.get(url).send().await?;
26        if resp.status() == reqwest::StatusCode::NOT_FOUND {
27            return Ok(None);
28        }
29
30        let origin: Origin = resp.json().await?;
31        Ok(Some(origin))
32    }
33
34    pub async fn set_origin(&self, namespace: &str, origin: Origin) -> Result<(), ApiError> {
35        let url = self.url.join(&format!("origin/{namespace}"))?;
36
37        let resp = self.client.post(url).json(&origin).send().await?;
38        resp.error_for_status()?;
39
40        Ok(())
41    }
42
43    pub async fn delete_origin(&self, namespace: &str) -> Result<(), ApiError> {
44        let url = self.url.join(&format!("origin/{namespace}"))?;
45
46        let resp = self.client.delete(url).send().await?;
47        resp.error_for_status()?;
48
49        Ok(())
50    }
51
52    pub async fn patch_origin(&self, namespace: &str, origin: Origin) -> Result<(), ApiError> {
53        let url = self.url.join(&format!("origin/{namespace}"))?;
54
55        let resp = self.client.patch(url).json(&origin).send().await?;
56        resp.error_for_status()?;
57
58        Ok(())
59    }
60}