json_ld_core/loader/
chain.rs

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