stac_validate/lib.rs
1//! Validate STAC objects with [json-schema](https://json-schema.org/).
2//!
3//! # Examples
4//!
5//! Validation is provided via the [Validate] trait:
6//!
7//! ```
8//! use stac::Item;
9//! use stac_validate::Validate;
10//!
11//! #[tokio::main]
12//! async fn main() {
13//! Item::new("an-id").validate().await.unwrap();
14//! }
15//! ```
16//!
17//! All fetched schemas are cached, so if you're you're doing multiple
18//! validations, you should re-use the same [Validator]:
19//!
20//! ```
21//! use stac::Item;
22//! use stac_validate::Validator;
23//!
24//! #[tokio::main]
25//! async fn main() {
26//! let mut items: Vec<_> = (0..10).map(|n| Item::new(format!("item-{}", n))).collect();
27//! let mut validator = Validator::new().await.unwrap();
28//! for item in items {
29//! validator.validate(&item).await.unwrap();
30//! }
31//! }
32//! ```
33//!
34//! [Validator] is cheap to clone, so you are encouraged to validate a large
35//! number of objects at the same time if that's your use-case.
36
37use serde::Serialize;
38
39mod error;
40mod validator;
41use async_trait::async_trait;
42
43pub use {error::Error, validator::Validator};
44
45/// Public result type.
46pub type Result<T> = std::result::Result<T, Error>;
47
48/// Validate any serializable object with [json-schema](https://json-schema.org/)
49#[async_trait]
50pub trait Validate: Serialize + Sized {
51 /// Validates this object.
52 ///
53 /// If the object fails validation, this will return an [Error::Validation]
54 /// which contains a vector of all of the validation errors.
55 ///
56 /// If you're doing multiple validations, use [Validator::validate], which
57 /// will re-use cached schemas.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use stac::Item;
63 /// use stac_validate::Validate;
64 ///
65 /// #[tokio::main]
66 /// async fn main() {
67 /// let mut item = Item::new("an-id");
68 /// item.validate().await.unwrap();
69 /// }
70 /// ```
71 async fn validate(&self) -> Result<()> {
72 let mut validator = Validator::new().await?;
73 validator.validate(self).await
74 }
75}
76
77impl<T: Serialize + Send + Sync> Validate for T {}
78
79/// Returns a string suitable for use as a HTTP user agent.
80pub fn user_agent() -> &'static str {
81 concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"))
82}