mirror of
https://github.com/n08i40k/schedule-parser-rusted.git
synced 2025-12-07 02:07:48 +03:00
Обновление документации.
This commit is contained in:
@@ -16,19 +16,19 @@ use std::fmt::Debug;
|
||||
#[status_code = "actix_web::http::StatusCode::UNAUTHORIZED"]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum Error {
|
||||
/// В запросе отсутствует заголовок Authorization
|
||||
/// There is no Authorization header in the request.
|
||||
#[display("No Authorization header found")]
|
||||
NoHeader,
|
||||
|
||||
/// Неизвестный тип авторизации, отличающийся от Bearer
|
||||
/// Unknown authorization type other than Bearer.
|
||||
#[display("Bearer token is required")]
|
||||
UnknownAuthorizationType,
|
||||
|
||||
/// Токен не действителен
|
||||
/// Invalid or expired access token.
|
||||
#[display("Invalid or expired access token")]
|
||||
InvalidAccessToken,
|
||||
|
||||
/// Пользователь привязанный к токену не найден в базе данных
|
||||
/// The user bound to the token is not found in the database.
|
||||
#[display("No user associated with access token")]
|
||||
NoUser,
|
||||
}
|
||||
@@ -39,7 +39,7 @@ impl Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Экстрактор пользователя из запроса с токеном
|
||||
/// User extractor from request with Bearer access token.
|
||||
impl FromRequestSync for User {
|
||||
type Error = actix_web::Error;
|
||||
|
||||
@@ -87,7 +87,7 @@ impl<const FCM: bool> UserExtractor<{ FCM }> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Экстрактор пользователя и дополнительных параметров из запроса с токеном
|
||||
/// Extractor of user and additional parameters from request with Bearer token.
|
||||
impl<const FCM: bool> FromRequestSync for UserExtractor<{ FCM }> {
|
||||
type Error = actix_web::Error;
|
||||
|
||||
|
||||
@@ -2,26 +2,64 @@ use actix_web::dev::Payload;
|
||||
use actix_web::{FromRequest, HttpRequest};
|
||||
use futures_util::future::LocalBoxFuture;
|
||||
use std::future::{Ready, ready};
|
||||
use std::ops;
|
||||
|
||||
/// Асинхронный экстрактор объектов из запроса
|
||||
/// # Async extractor.
|
||||
|
||||
/// Asynchronous object extractor from a query.
|
||||
pub struct AsyncExtractor<T>(T);
|
||||
|
||||
impl<T> AsyncExtractor<T> {
|
||||
#[allow(dead_code)]
|
||||
/// Получение объекта, извлечённого с помощью экстрактора
|
||||
/// Retrieve the object extracted with the extractor.
|
||||
pub fn into_inner(self) -> T {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ops::Deref for AsyncExtractor<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ops::DerefMut for AsyncExtractor<T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub trait FromRequestAsync: Sized {
|
||||
type Error: Into<actix_web::Error>;
|
||||
|
||||
/// Асинхронная функция для извлечения данных из запроса
|
||||
/// Asynchronous function for extracting data from a query.
|
||||
///
|
||||
/// returns: Result<Self, Self::Error>
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// struct User {
|
||||
/// pub id: String,
|
||||
/// pub username: String,
|
||||
/// }
|
||||
///
|
||||
/// // TODO: Я вообще этот экстрактор не использую, нахуя мне тогда писать пример, если я не ебу как его использовать. Я забыл.
|
||||
///
|
||||
/// #[get("/")]
|
||||
/// fn get_user_async(
|
||||
/// user: web::AsyncExtractor<User>,
|
||||
/// ) -> web::Json<User> {
|
||||
/// let user = user.into_inner();
|
||||
///
|
||||
/// web::Json(user)
|
||||
/// }
|
||||
/// ```
|
||||
async fn from_request_async(req: HttpRequest, payload: Payload) -> Result<Self, Self::Error>;
|
||||
}
|
||||
|
||||
/// Реализация треита FromRequest для всех асинхронных экстракторов
|
||||
impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
|
||||
type Error = T::Error;
|
||||
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
||||
@@ -37,24 +75,72 @@ impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Синхронный экстрактор объектов из запроса
|
||||
/// # Sync extractor.
|
||||
|
||||
/// Synchronous object extractor from a query.
|
||||
pub struct SyncExtractor<T>(T);
|
||||
|
||||
impl<T> SyncExtractor<T> {
|
||||
/// Получение объекта, извлечённого с помощью экстрактора
|
||||
/// Retrieving an object extracted with the extractor.
|
||||
pub fn into_inner(self) -> T {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ops::Deref for SyncExtractor<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ops::DerefMut for SyncExtractor<T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub trait FromRequestSync: Sized {
|
||||
type Error: Into<actix_web::Error>;
|
||||
|
||||
/// Синхронная функция для извлечения данных из запроса
|
||||
/// Synchronous function for extracting data from a query.
|
||||
///
|
||||
/// returns: Result<Self, Self::Error>
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// struct User {
|
||||
/// pub id: String,
|
||||
/// pub username: String,
|
||||
/// }
|
||||
///
|
||||
/// impl FromRequestSync for User {
|
||||
/// type Error = actix_web::Error;
|
||||
///
|
||||
/// fn from_request_sync(req: &HttpRequest, _: &mut Payload) -> Result<Self, Self::Error> {
|
||||
/// // do magic here.
|
||||
///
|
||||
/// Ok(User {
|
||||
/// id: "qwerty".to_string(),
|
||||
/// username: "n08i40k".to_string()
|
||||
/// })
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// #[get("/")]
|
||||
/// fn get_user_sync(
|
||||
/// user: web::SyncExtractor<User>,
|
||||
/// ) -> web::Json<User> {
|
||||
/// let user = user.into_inner();
|
||||
///
|
||||
/// web::Json(user)
|
||||
/// }
|
||||
/// ```
|
||||
fn from_request_sync(req: &HttpRequest, payload: &mut Payload) -> Result<Self, Self::Error>;
|
||||
}
|
||||
|
||||
/// Реализация треита FromRequest для всех синхронных экстракторов
|
||||
impl<T: FromRequestSync> FromRequest for SyncExtractor<T> {
|
||||
type Error = T::Error;
|
||||
type Future = Ready<Result<Self, Self::Error>>;
|
||||
|
||||
Reference in New Issue
Block a user