pocketbase_rs/records/auth/
auth_refresh.rs

1use crate::error::RequestError;
2use crate::{AuthStore, Collection};
3
4impl Collection<'_> {
5    /// Returns a new auth response (token and record data) for an **already authenticated record**.
6    ///
7    /// This method is usually called by users on page/screen reload to ensure that the previously stored data in `pb.auth_store()` is still valid and up-to-date.
8    ///
9    /// # Example
10    /// ```rust,ignore
11    /// let auth_data = pb.collection("users")
12    ///     .auth_refresh()
13    ///     .await?;
14    ///
15    /// println!("New token: {}", auth_data.token);
16    /// ```
17    pub async fn auth_refresh(&mut self) -> Result<AuthStore, RequestError> {
18        let url = format!(
19            "{}/api/collections/{}/auth-refresh",
20            self.client.base_url(),
21            self.name
22        );
23
24        let request = self.client.request_post(&url).send().await;
25
26        match request {
27            Ok(response) => match response.status() {
28                reqwest::StatusCode::OK => {
29                    let Ok(auth_store) = response.json::<AuthStore>().await else {
30                        return Err(RequestError::Unhandled);
31                    };
32
33                    self.client.update_auth_store(auth_store.clone());
34
35                    Ok(auth_store)
36                }
37
38                reqwest::StatusCode::UNAUTHORIZED => Err(RequestError::Unauthorized),
39                reqwest::StatusCode::FORBIDDEN => Err(RequestError::Forbidden),
40                reqwest::StatusCode::NOT_FOUND => Err(RequestError::NotFound),
41
42                _ => Err(RequestError::Unhandled),
43            },
44            Err(_) => Err(RequestError::Unhandled),
45        }
46    }
47}