lexa_framework/extract/
env.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
3// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
4// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
5// ┃                                                                           ┃
6// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
7// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
8// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
9// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
10
11use axum::http;
12
13use crate::ApplicationEnvInterface;
14
15// --------- //
16// Structure //
17// --------- //
18
19pub struct Env<E>(pub E);
20
21// ----------- //
22// Énumération //
23// ----------- //
24
25#[derive(Debug)]
26#[derive(thiserror::Error)]
27pub enum MissingEnvError {
28	#[error("\n\t{}: {0}", std::any::type_name::<Self>())]
29	Extension(#[from] axum::extract::rejection::ExtensionRejection),
30}
31
32// -------------- //
33// Implémentation // -> Interface
34// -------------- //
35
36#[async_trait::async_trait]
37impl<S, C> axum::extract::FromRequestParts<S> for Env<C>
38where
39	C: 'static,
40	C: ApplicationEnvInterface,
41	S: Send + Sync,
42{
43	type Rejection = MissingEnvError;
44
45	async fn from_request_parts(
46		parts: &mut axum::http::request::Parts,
47		state: &S,
48	) -> Result<Self, Self::Rejection> {
49		axum::Extension::<C>::from_request_parts(parts, state)
50			.await
51			.map(|axum::Extension(ext)| Self(ext))
52			.map_err(MissingEnvError::Extension)
53	}
54}
55
56impl axum::response::IntoResponse for MissingEnvError {
57	fn into_response(self) -> axum::response::Response {
58		let err_status = http::StatusCode::INTERNAL_SERVER_ERROR;
59		let err_body = self.to_string();
60		(err_status, err_body).into_response()
61	}
62}