pocketbase_rs/records/crud/
delete.rs

1use crate::Collection;
2use thiserror::Error;
3
4#[derive(Error, Debug)]
5pub enum DeleteError {
6    /// Communication with the `PocketBase` API was successful,
7    /// but returned a [400 Bad Request]("https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400") HTTP error response.
8    ///
9    /// Failed to delete record. Make sure that the record is not part of a required relation reference. `PocketBase`.
10    #[error(
11        "Failed to delete record. Make sure that the record is not part of a required relation reference."
12    )]
13    BadRequest,
14    /// Communication with the `PocketBase` API was successful,
15    /// but returned a [403 Forbidden]("https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403") HTTP error response.
16    ///
17    /// You are not allowed to perform this request.
18    #[error("You are not allowed to perform this request.")]
19    Forbidden,
20    /// Communication with the `PocketBase` API was successful,
21    /// but returned a [404 Not Found]("https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404") HTTP error response.
22    ///
23    /// The requested resource wasn't found.
24    #[error("The requested resource wasn't found.")]
25    NotFound,
26    /// Communication with the `PocketBase` API failed.
27    ///
28    /// This could be caused by an internet outage, an error in the link given to the `PocketBase` SDK
29    /// and similar errors.
30    #[error("The communication with the PocketBase API failed: {0}")]
31    Unreachable(String),
32    /// An unexpected error occurred.
33    /// The response from the `PocketBase` instance API was unexpected.
34    /// If you think its an error, please [open an issue on GitHub]("https://github.com/fromhorizons/pocketbase-rs/issues").
35    #[error("An unhandled status code was returned by the PocketBase API: {0}")]
36    UnexpectedResponse(String),
37}
38
39impl<'a> Collection<'a> {
40    /// Delete a single record.
41    ///
42    /// # Example
43    /// ```rust,ignore
44    /// pb.collection("articles")
45    ///     .delete("RECORD_ID")
46    ///     .await?;
47    /// ```
48    pub async fn delete(&self, record_id: &'a str) -> Result<(), DeleteError> {
49        // Validate record_id
50        if record_id.is_empty() {
51            return Err(DeleteError::BadRequest);
52        }
53
54        let endpoint = format!(
55            "{}/api/collections/{}/records/{}",
56            self.client.base_url, self.name, record_id
57        );
58        let request = self.client.request_delete(&endpoint).send().await;
59
60        match request {
61            Ok(response) => match response.status() {
62                reqwest::StatusCode::NO_CONTENT | reqwest::StatusCode::OK => Ok(()),
63                reqwest::StatusCode::BAD_REQUEST => Err(DeleteError::BadRequest),
64                reqwest::StatusCode::FORBIDDEN => Err(DeleteError::Forbidden),
65                reqwest::StatusCode::NOT_FOUND => Err(DeleteError::NotFound),
66                _ => Err(DeleteError::UnexpectedResponse(format!(
67                    "Status: {}, Collection: {}, Record: {}",
68                    response.status(),
69                    self.name,
70                    record_id
71                ))),
72            },
73            Err(e) => {
74                if e.is_timeout() {
75                    Err(DeleteError::Unreachable("Request timed out".to_string()))
76                } else if e.is_connect() {
77                    Err(DeleteError::Unreachable(
78                        "Failed to connect to server".to_string(),
79                    ))
80                } else {
81                    Err(DeleteError::Unreachable(e.to_string()))
82                }
83            }
84        }
85    }
86}