Skip to main content

json_ld/core/loader/
chain.rs

1use core::fmt;
2
3use crate::{JsonLdDocument, JsonLdLoadError};
4use rdf_syntax::Iri;
5
6use super::AsyncJsonLdLoader;
7
8/// * [`JsonLdChainLoader`]: loads document from the first loader, otherwise falls back to the second one.
9///
10/// This can be useful for combining, for example,
11/// a [`JsonLdFsLoader`](super::JsonLdFsLoader) for loading some contexts from a local cache,
12/// and a [`JsonLdReqwestLoader`](super::JsonLdReqwestLoader) for loading any other context from the web.
13///
14/// Note that it is also possible to nest several [`JsonLdChainLoader`]s,
15/// to combine more than two loaders.
16pub struct JsonLdChainLoader<L1, L2>(L1, L2);
17
18impl<L1, L2> JsonLdChainLoader<L1, L2> {
19	/// Build a new chain loader
20	pub fn new(l1: L1, l2: L2) -> Self {
21		JsonLdChainLoader(l1, l2)
22	}
23}
24
25impl<L1, L2> AsyncJsonLdLoader for JsonLdChainLoader<L1, L2>
26where
27	L1: AsyncJsonLdLoader,
28	L2: AsyncJsonLdLoader,
29{
30	async fn async_load(&self, url: &Iri) -> Result<JsonLdDocument, JsonLdLoadError> {
31		match self.0.async_load(url).await {
32			Ok(doc) => Ok(doc),
33			Err(JsonLdLoadError { cause: e1, .. }) => match self.1.async_load(url).await {
34				Ok(doc) => Ok(doc),
35				Err(JsonLdLoadError { target, cause: e2 }) => {
36					Err(JsonLdLoadError::new(target, Error(e1, e2)))
37				}
38			},
39		}
40	}
41}
42
43/// Either-or error.
44#[derive(Debug)]
45pub struct Error(pub anyhow::Error, pub anyhow::Error);
46
47impl fmt::Display for Error {
48	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49		let Error(e1, e2) = self;
50		write!(f, "{e1}, then {e2}")
51	}
52}
53
54impl std::error::Error for Error {}