async-graphql/src/guard.rs

34 lines
868 B
Rust
Raw Normal View History

2020-05-01 23:57:34 +00:00
//! Field guards
use crate::{Context, FieldResult};
/// Field guard
///
/// Guard is a precondition for a field that is resolved if `Ok(()` is returned, otherwise an error is returned.
#[async_trait::async_trait]
pub trait Guard {
#[allow(missing_docs)]
async fn check(&self, ctx: &Context<'_>) -> FieldResult<()>;
}
/// An extension trait for `Guard`
pub trait GuardExt: Guard + Sized {
/// Merge the two guards.
2020-05-14 14:13:28 +00:00
fn and<R: Guard>(self, other: R) -> And<Self, R> {
And(self, other)
2020-05-01 23:57:34 +00:00
}
}
impl<T: Guard> GuardExt for T {}
/// Guard for `GuardExt::and`
2020-05-14 14:13:28 +00:00
pub struct And<A: Guard, B: Guard>(A, B);
2020-05-01 23:57:34 +00:00
#[async_trait::async_trait]
2020-05-14 14:13:28 +00:00
impl<A: Guard + Send + Sync, B: Guard + Send + Sync> Guard for And<A, B> {
2020-05-01 23:57:34 +00:00
async fn check(&self, ctx: &Context<'_>) -> FieldResult<()> {
self.0.check(ctx).await?;
self.1.check(ctx).await
}
}