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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
use std::ops::Deref;
use poem::{Error, FromRequest, Request, RequestBody, Result, Route};
use crate::registry::{
MetaApi, MetaOAuthScope, MetaParamIn, MetaRequest, MetaResponse, MetaResponses, MetaSchemaRef,
Registry,
};
/// API extractor types.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ApiExtractorType {
/// A request object.
RequestObject,
/// A request parameter.
Parameter,
/// A security scheme.
SecurityScheme,
/// A poem extractor.
PoemExtractor,
}
#[doc(hidden)]
pub struct UrlQuery(pub Vec<(String, String)>);
impl Deref for UrlQuery {
type Target = Vec<(String, String)>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl UrlQuery {
#[allow(missing_docs)]
pub fn get_all<'a, 'b: 'a>(&'b self, name: &'a str) -> impl Iterator<Item = &'b String> + 'a {
self.0
.iter()
.filter(move |(n, _)| n == name)
.map(|(_, value)| value)
}
#[allow(missing_docs)]
pub fn get(&self, name: &str) -> Option<&String> {
self.get_all(name).next()
}
}
/// Options for the parameter extractor.
pub struct ExtractParamOptions<T> {
/// The name of this parameter.
pub name: &'static str,
/// The default value of this parameter.
pub default_value: Option<fn() -> T>,
}
impl<T> Default for ExtractParamOptions<T> {
fn default() -> Self {
Self {
name: "",
default_value: None,
}
}
}
/// Represents a OpenAPI extractor.
///
/// # Provided Implementations
///
/// - **Path<T: Type>**
///
/// Extract the parameters in the request path into
/// [`Path`](crate::param::Path).
///
/// - **Query<T: Type>**
///
/// Extract the parameters in the query string into
/// [`Query`](crate::param::Query).
///
/// - **Header<T: Type>**
///
/// Extract the parameters in the request header into
/// [`Header`](crate::param::Header).
///
/// - **Cookie<T: Type>**
///
/// Extract the parameters in the cookie into
/// [`Cookie`](crate::param::Cookie).
///
/// - **CookiePrivate<T: Type>**
///
/// Extract the parameters in the private cookie into
/// [`CookiePrivate`](crate::param::CookiePrivate).
///
/// - **CookieSigned<T: Type>**
///
/// Extract the parameters in the signed cookie into
/// [`CookieSigned`](crate::param::CookieSigned).
///
/// - **Binary<T>**
///
/// Extract the request body as binary into
/// [`Binary`](crate::payload::Binary).
///
/// - **Json<T>**
///
/// Parse the request body in `JSON` format into
/// [`Json`](crate::payload::Json).
///
/// - **PlainText<T>**
///
/// Extract the request body as utf8 string into
/// [`PlainText`](crate::payload::PlainText).
///
/// - **Any type derived from the [`ApiRequest`](crate::ApiRequest) macro**
///
/// Extract the complex request body derived from the `ApiRequest` macro.
///
/// - **Any type derived from the [`Multipart`](crate::Multipart) macro**
///
/// Extract the multipart object derived from the `Multipart` macro.
///
/// - **Any type derived from the [`SecurityScheme`](crate::SecurityScheme)
/// macro**
///
/// Extract the authentication value derived from the `SecurityScheme`
/// macro.
///
/// - **T: poem::FromRequest**
///
/// Use Poem's extractor.
#[poem::async_trait]
#[allow(unused_variables)]
pub trait ApiExtractor<'a>: Sized {
/// The type of API extractor.
const TYPE: ApiExtractorType;
/// If it is `true`, it means that this parameter is required.
const PARAM_IS_REQUIRED: bool = false;
/// The parameter type.
type ParamType;
/// The raw parameter type for validators.
type ParamRawType;
/// Register related types to registry.
fn register(registry: &mut Registry) {}
/// Returns name of security scheme if this extractor is security scheme.
fn security_scheme() -> Option<&'static str> {
None
}
/// Returns the location of the parameter if this extractor is parameter.
fn param_in() -> Option<MetaParamIn> {
None
}
/// Returns the schema of the parameter if this extractor is parameter.
fn param_schema_ref() -> Option<MetaSchemaRef> {
None
}
/// Returns `MetaRequest` if this extractor is request object.
fn request_meta() -> Option<MetaRequest> {
None
}
/// Returns a reference to the raw type of this parameter.
fn param_raw_type(&self) -> Option<&Self::ParamRawType> {
None
}
/// Parse from the HTTP request.
async fn from_request(
request: &'a Request,
body: &mut RequestBody,
param_opts: ExtractParamOptions<Self::ParamType>,
) -> Result<Self>;
}
#[poem::async_trait]
impl<'a, T: FromRequest<'a>> ApiExtractor<'a> for T {
const TYPE: ApiExtractorType = ApiExtractorType::PoemExtractor;
type ParamType = ();
type ParamRawType = ();
async fn from_request(
request: &'a Request,
body: &mut RequestBody,
_param_opts: ExtractParamOptions<Self::ParamType>,
) -> Result<Self> {
T::from_request(request, body).await
}
}
/// Represents a OpenAPI responses object.
///
/// # Provided Implementations
///
/// - **Binary<T: Type>**
///
/// A binary response with content type `application/octet-stream`.
///
/// - **Json<T: Type>**
///
/// A JSON response with content type `application/json`.
///
/// - **PlainText<T: Type>**
///
/// A utf8 string response with content type `text/plain`.
///
/// - **Attachment<T: Type>**
///
/// A file download response, the content type is
/// `application/octet-stream`.
///
/// - **Response<T: Type>**
///
/// A response type use it to modify the status code and HTTP headers.
///
/// - **()**
///
/// It means that this API does not have any response body.
///
/// - **poem::Result<T: ApiResponse>**
///
/// It means that an error may occur in this API.
///
/// - **Any type derived from the [`ApiResponse`](crate::ApiResponse) macro**
///
/// A complex response derived from the `ApiResponse` macro.
pub trait ApiResponse: Sized {
/// If true, it means that the response object has a custom bad request
/// handler.
const BAD_REQUEST_HANDLER: bool = false;
/// Gets metadata of this response.
fn meta() -> MetaResponses;
/// Register the schema contained in this response object to the registry.
fn register(registry: &mut Registry);
/// Convert [`poem::Error`] to this response object.
#[allow(unused_variables)]
fn from_parse_request_error(err: Error) -> Self {
unreachable!()
}
}
impl ApiResponse for () {
fn meta() -> MetaResponses {
MetaResponses {
responses: vec![MetaResponse {
description: "",
status: Some(200),
content: vec![],
headers: vec![],
}],
}
}
fn register(_registry: &mut Registry) {}
}
impl<T: ApiResponse> ApiResponse for Result<T> {
const BAD_REQUEST_HANDLER: bool = T::BAD_REQUEST_HANDLER;
fn meta() -> MetaResponses {
T::meta()
}
fn register(registry: &mut Registry) {
T::register(registry);
}
fn from_parse_request_error(err: Error) -> Self {
Ok(T::from_parse_request_error(err))
}
}
/// Represents a OpenAPI tags.
pub trait Tags {
/// Register this tag type to registry.
fn register(&self, registry: &mut Registry);
/// Gets the tag name.
fn name(&self) -> &'static str;
}
/// Represents a OAuth scopes.
pub trait OAuthScopes {
/// Gets metadata of this object.
fn meta() -> Vec<MetaOAuthScope>;
/// Get the scope name.
fn name(&self) -> &'static str;
}
/// Represents a OpenAPI object.
pub trait OpenApi: Sized {
/// Gets metadata of this API object.
fn meta() -> Vec<MetaApi>;
/// Register some types to the registry.
fn register(registry: &mut Registry);
/// Adds all API endpoints to the routing object.
fn add_routes(self, route: Route) -> Route;
/// Combine two API objects into one.
fn combine<T: OpenApi>(self, other: T) -> CombinedAPI<Self, T> {
CombinedAPI(self, other)
}
}
/// API for the [`combine`](crate::OpenApi::combine) method.
pub struct CombinedAPI<A, B>(A, B);
impl<A: OpenApi, B: OpenApi> OpenApi for CombinedAPI<A, B> {
fn meta() -> Vec<MetaApi> {
let mut metadata = A::meta();
metadata.extend(B::meta());
metadata
}
fn register(registry: &mut Registry) {
A::register(registry);
B::register(registry);
}
fn add_routes(self, route: Route) -> Route {
self.1.add_routes(self.0.add_routes(route))
}
}