| 1 | #![cfg(all(target_arch = "wasm32", target_os = "wasi", feature = "resolve-async"))] |
| 2 | |
| 3 | use futures::executor::block_on; |
| 4 | use jsonschema::{async_options, AsyncRetrieve, Uri}; |
| 5 | use serde_json::{json, Value}; |
| 6 | use std::collections::HashMap; |
| 7 | |
| 8 | struct MapAsyncRetriever { |
| 9 | schemas: HashMap<String, Value>, |
| 10 | } |
| 11 | |
| 12 | impl MapAsyncRetriever { |
| 13 | fn new(entries: impl IntoIterator<Item = (String, Value)>) -> Self { |
| 14 | Self { |
| 15 | schemas: entries.into_iter().collect(), |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | #[async_trait::async_trait(?Send)] |
| 21 | impl AsyncRetrieve for MapAsyncRetriever { |
| 22 | async fn retrieve( |
| 23 | &self, |
| 24 | uri: &Uri<String>, |
| 25 | ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> { |
| 26 | self.schemas |
| 27 | .get(uri.as_str()) |
| 28 | .cloned() |
| 29 | .ok_or_else(|| "schema not found".into()) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | #[test] |
| 34 | fn async_retriever_resolves_refs_on_wasi() { |
| 35 | block_on(async { |
| 36 | let schema = json!({ |
| 37 | "$ref": "https://example.com/user.json" |
| 38 | }); |
| 39 | |
| 40 | let retriever = MapAsyncRetriever::new([( |
| 41 | "https://example.com/user.json".to_string(), |
| 42 | json!({ |
| 43 | "$id": "https://example.com/user.json", |
| 44 | "type": "object", |
| 45 | "properties": { |
| 46 | "name": { "type": "string" }, |
| 47 | "age": { "type": "integer", "minimum": 0 } |
| 48 | }, |
| 49 | "required": ["name"] |
| 50 | }), |
| 51 | )]); |
| 52 | |
| 53 | let validator = async_options() |
| 54 | .with_retriever(retriever) |
| 55 | .build(&schema) |
| 56 | .await |
| 57 | .expect("validator builds on wasm32-wasi"); |
| 58 | |
| 59 | assert!(validator.is_valid(&json!({"name": "Ferris", "age": 13}))); |
| 60 | assert!(!validator.is_valid(&json!({"name": 42}))); |
| 61 | }); |
| 62 | } |