Skip to main content

jsonld_core/loader/
chain.rs

1use crate::LoadError;
2use iri_rs::{Iri, IriBuf};
3
4use super::{Loader, RemoteDocument};
5
6/// * [`ChainLoader`]: loads document from the first loader, otherwise falls back to the second one.
7///
8/// This can be useful for combining, for example,
9/// an [`FsLoader`](super::FsLoader) for loading some contexts from a local cache,
10/// and a [`ReqwestLoader`](super::ReqwestLoader) for loading any other context from the web.
11///
12/// Note that it is also possible to nest several [`ChainLoader`]s,
13/// to combine more than two loaders.
14#[derive(Debug, Clone)]
15pub struct ChainLoader<L1, L2>(L1, L2);
16
17impl<L1, L2> ChainLoader<L1, L2> {
18    /// Build a new chain loader
19    pub fn new(l1: L1, l2: L2) -> Self {
20        ChainLoader(l1, l2)
21    }
22}
23
24impl<L1, L2> Loader for ChainLoader<L1, L2>
25where
26    L1: Loader,
27    L2: Loader,
28{
29    type Error = ChainError<L1::Error, L2::Error>;
30
31    async fn load(&self, url: Iri<&str>) -> Result<RemoteDocument<IriBuf>, LoadError<Self::Error>> {
32        match self.0.load(url).await {
33            Ok(doc) => Ok(doc),
34            Err(LoadError { source: e1, .. }) => match self.1.load(url).await {
35                Ok(doc) => Ok(doc),
36                Err(LoadError { target, source: e2 }) => Err(LoadError::new(target, ChainError::Both(e1, e2))),
37            },
38        }
39    }
40}
41
42/// Combined error from two chained loaders.
43///
44/// The second loader is only consulted after the first has failed, so a
45/// chain failure always carries both errors.
46#[derive(Debug, thiserror::Error)]
47pub enum ChainError<A, B> {
48    /// Both loaders failed.
49    #[error("both loaders failed: {0}, then {1}")]
50    Both(A, B),
51}