1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use coi::{Container, Inject};
use rocket::{
http::Status,
outcome::IntoOutcome as _,
request::{FromRequest, Outcome},
Request, State,
};
use std::{marker::PhantomData, sync::Arc};
pub use coi_rocket_derive::inject;
#[doc(hidden)]
pub trait ContainerKey<T>
where
T: Inject + ?Sized,
{
const KEY: &'static str;
}
#[doc(hidden)]
pub struct Injected<T, K>(pub T, pub PhantomData<K>);
impl<T, K> Injected<T, K> {
#[doc(hidden)]
pub fn new(injected: T) -> Self {
Self(injected, PhantomData)
}
}
struct ScopedContainer(Container);
#[derive(Debug)]
pub enum Error {
Coi(coi::Error),
MissingContainer,
}
impl<'a, 'r> FromRequest<'a, 'r> for &'a ScopedContainer {
type Error = Error;
fn from_request(req: &'a Request<'r>) -> Outcome<&'a ScopedContainer, Error> {
req.local_cache(|| {
let container = req.guard::<State<Container>>().succeeded()?;
Some(ScopedContainer(container.scoped()))
})
.as_ref()
.into_outcome((Status::InternalServerError, Error::MissingContainer))
}
}
impl<'a, 'r, T, K> FromRequest<'a, 'r> for Injected<Arc<T>, K>
where
T: Inject + ?Sized,
K: ContainerKey<T>,
{
type Error = Error;
fn from_request(req: &'a Request<'r>) -> Outcome<Injected<Arc<T>, K>, Error> {
let container = match req.guard::<&ScopedContainer>() {
Outcome::Success(container) => container,
Outcome::Failure(f) => return Outcome::Failure(f),
Outcome::Forward(f) => return Outcome::Forward(f),
};
container
.0
.resolve::<T>(<K as ContainerKey<T>>::KEY)
.map(Injected::new)
.map_err(Error::Coi)
.into_outcome(Status::InternalServerError)
}
}