use std::{rc::Rc, time::Instant};
#[cfg(doc)]
use super::use_query;
use crate::query::QueryError;
pub struct QueryResult<T> {
pub(super) data: Option<Rc<T>>,
pub(super) error: Option<QueryError>,
pub(super) is_fetching: bool,
pub(super) is_placeholder: bool,
pub(super) is_stale: bool,
pub(super) updated_at: Option<Instant>,
}
#[derive(Debug)]
pub enum QueryState<'a, T> {
Pending,
Error(&'a QueryError),
Success(&'a T),
}
impl<T> QueryResult<T> {
#[must_use]
pub fn state(&self) -> QueryState<'_, T> {
match (&self.data, &self.error) {
(Some(data), _) => QueryState::Success(data),
(None, Some(error)) => QueryState::Error(error),
(None, None) => QueryState::Pending,
}
}
#[must_use]
pub fn data(&self) -> Option<&T> {
self.data.as_deref()
}
#[must_use]
pub fn data_rc(&self) -> Option<Rc<T>> {
self.data.clone()
}
#[must_use]
pub fn error(&self) -> Option<&QueryError> {
self.error.as_ref()
}
#[must_use]
pub fn is_pending(&self) -> bool {
self.data.is_none() && self.error.is_none()
}
#[must_use]
pub fn is_success(&self) -> bool {
self.data.is_some()
}
#[must_use]
pub fn is_error(&self) -> bool {
self.error.is_some()
}
#[must_use]
pub fn is_fetching(&self) -> bool {
self.is_fetching
}
#[must_use]
pub fn is_loading(&self) -> bool {
self.is_pending() && self.is_fetching
}
#[must_use]
pub fn is_placeholder_data(&self) -> bool {
self.is_placeholder
}
#[must_use]
pub fn is_stale(&self) -> bool {
self.is_stale
}
#[must_use]
pub fn updated_at(&self) -> Option<Instant> {
self.updated_at
}
pub fn suspend(self) -> Result<Rc<T>, crate::query::Suspend> {
match (self.data, self.error) {
(Some(data), _) => Ok(data),
(None, Some(error)) => Err(crate::query::Suspend::Failed(error)),
(None, None) => Err(crate::query::Suspend::Pending),
}
}
}
impl<T> Clone for QueryResult<T> {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
error: self.error.clone(),
is_fetching: self.is_fetching,
is_placeholder: self.is_placeholder,
is_stale: self.is_stale,
updated_at: self.updated_at,
}
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for QueryResult<T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("QueryResult")
.field("data", &self.data)
.field("error", &self.error)
.field("is_fetching", &self.is_fetching)
.finish_non_exhaustive()
}
}