mirror of
https://gitlab.com/msrd0/gotham-restful.git
synced 2025-02-22 20:52:27 +00:00
docs: use [Type] syntax from rust 1.48
This commit is contained in:
parent
ed1bbbd1fb
commit
4ae860dd32
11 changed files with 71 additions and 70 deletions
|
@ -75,6 +75,7 @@ pub enum AuthSource {
|
|||
This trait will help the auth middleware to determine the validity of an authentication token.
|
||||
|
||||
A very basic implementation could look like this:
|
||||
|
||||
```
|
||||
# use gotham_restful::{AuthHandler, State};
|
||||
#
|
||||
|
@ -93,7 +94,7 @@ pub trait AuthHandler<Data> {
|
|||
fn jwt_secret<F: FnOnce() -> Option<Data>>(&self, state: &mut State, decode_data: F) -> Option<Vec<u8>>;
|
||||
}
|
||||
|
||||
/// An `AuthHandler` returning always the same secret. See `AuthMiddleware` for a usage example.
|
||||
/// An [AuthHandler] returning always the same secret. See [AuthMiddleware] for a usage example.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StaticAuthHandler {
|
||||
secret: Vec<u8>
|
||||
|
|
17
src/cors.rs
17
src/cors.rs
|
@ -59,7 +59,7 @@ impl Origin {
|
|||
This is the configuration that the CORS handler will follow. Its default configuration is basically
|
||||
not to touch any responses, resulting in the browser's default behaviour.
|
||||
|
||||
To change settings, you need to put this type into gotham's [`State`]:
|
||||
To change settings, you need to put this type into gotham's [State]:
|
||||
|
||||
```rust,no_run
|
||||
# use gotham::{router::builder::*, pipeline::{new_pipeline, single::single_pipeline}, state::State};
|
||||
|
@ -113,8 +113,6 @@ gotham::start("127.0.0.1:8080", build_router((), pipeline_set, |route| {
|
|||
});
|
||||
}));
|
||||
```
|
||||
|
||||
[`State`]: ../gotham/state/struct.State.html
|
||||
*/
|
||||
#[derive(Clone, Debug, Default, NewMiddleware, StateData)]
|
||||
pub struct CorsConfig {
|
||||
|
@ -142,13 +140,12 @@ impl Middleware for CorsConfig {
|
|||
Handle CORS for a non-preflight request. This means manipulating the `res` HTTP headers so that
|
||||
the response is aligned with the `state`'s [CorsConfig].
|
||||
|
||||
If you are using the [Resource](crate::Resource) type (which is the recommended way), you'll never have to call
|
||||
this method. However, if you are writing your own handler method, you might want to call this
|
||||
after your request to add the required CORS headers.
|
||||
If you are using the [Resource](crate::Resource) type (which is the recommended way), you'll never
|
||||
have to call this method. However, if you are writing your own handler method, you might want to
|
||||
call this after your request to add the required CORS headers.
|
||||
|
||||
For further information on CORS, read [https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).
|
||||
|
||||
[`CorsConfig`]: ./struct.CorsConfig.html
|
||||
For further information on CORS, read
|
||||
[https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).
|
||||
*/
|
||||
pub fn handle_cors(state: &State, res: &mut Response<Body>) {
|
||||
let config = CorsConfig::try_borrow_from(state);
|
||||
|
@ -195,7 +192,7 @@ where
|
|||
P: RefUnwindSafe + Send + Sync + 'static
|
||||
{
|
||||
/// Handle a preflight request on `path` for `method`. To configure the behaviour, use
|
||||
/// [`CorsConfig`](struct.CorsConfig.html).
|
||||
/// [CorsConfig].
|
||||
fn cors(&mut self, path: &str, method: Method);
|
||||
}
|
||||
|
||||
|
|
19
src/lib.rs
19
src/lib.rs
|
@ -1,17 +1,26 @@
|
|||
#![allow(clippy::tabs_in_doc_comments)]
|
||||
#![warn(missing_debug_implementations, rust_2018_idioms)]
|
||||
#![deny(broken_intra_doc_links)]
|
||||
#![forbid(unsafe_code)]
|
||||
/*!
|
||||
This crate is an extension to the popular [gotham web framework][gotham] for Rust. It allows you to
|
||||
create resources with assigned methods that aim to be a more convenient way of creating handlers
|
||||
for requests.
|
||||
|
||||
# Design Goals
|
||||
# Features
|
||||
|
||||
This is an opinionated framework on top of [gotham]. Unless your web server handles mostly JSON as
|
||||
request/response bodies and does that in a RESTful way, this framework is probably a bad fit for
|
||||
your application. The ultimate goal of gotham-restful is to provide a way to write a RESTful
|
||||
web server in Rust as convenient as possible with the least amount of boilerplate neccessary.
|
||||
- Automatically parse **JSON** request and produce response bodies
|
||||
- Allow using **raw** request and response bodies
|
||||
- Convenient **macros** to create responses that can be registered with gotham's router
|
||||
- Auto-Generate an **OpenAPI** specification for your API
|
||||
- Manage **CORS** headers so you don't have to
|
||||
- Manage **Authentication** with JWT
|
||||
- Integrate diesel connection pools for easy **database** integration
|
||||
|
||||
# Safety
|
||||
|
||||
This crate is just as safe as you'd expect from anything written in safe Rust - and
|
||||
`#![forbid(unsafe_code)]` ensures that no unsafe was used.
|
||||
|
||||
# Methods
|
||||
|
||||
|
|
|
@ -16,9 +16,7 @@ use uuid::Uuid;
|
|||
/**
|
||||
This struct needs to be available for every type that can be part of an OpenAPI Spec. It is
|
||||
already implemented for primitive types, String, Vec, Option and the like. To have it available
|
||||
for your type, simply derive from [`OpenapiType`].
|
||||
|
||||
[`OpenapiType`]: trait.OpenapiType.html
|
||||
for your type, simply derive from [OpenapiType].
|
||||
*/
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct OpenapiSchema {
|
||||
|
@ -46,7 +44,7 @@ impl OpenapiSchema {
|
|||
}
|
||||
}
|
||||
|
||||
/// Convert this schema to an `openapiv3::Schema` that can be serialized to the OpenAPI Spec.
|
||||
/// Convert this schema to an [openapiv3::Schema] that can be serialized to the OpenAPI Spec.
|
||||
pub fn into_schema(self) -> Schema {
|
||||
Schema {
|
||||
schema_data: SchemaData {
|
||||
|
@ -61,7 +59,7 @@ impl OpenapiSchema {
|
|||
|
||||
/**
|
||||
This trait needs to be implemented by every type that is being used in the OpenAPI Spec. It gives
|
||||
access to the [`OpenapiSchema`] of this type. It is provided for primitive types, String and the
|
||||
access to the [OpenapiSchema] of this type. It is provided for primitive types, String and the
|
||||
like. For use on your own types, there is a derive macro:
|
||||
|
||||
```
|
||||
|
@ -72,8 +70,6 @@ struct MyResponse {
|
|||
message: String
|
||||
}
|
||||
```
|
||||
|
||||
[`OpenapiSchema`]: struct.OpenapiSchema.html
|
||||
*/
|
||||
pub trait OpenapiType {
|
||||
fn schema() -> OpenapiSchema;
|
||||
|
|
|
@ -30,13 +30,13 @@ pub trait ResourceMethod {
|
|||
}
|
||||
}
|
||||
|
||||
/// The read_all [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The read_all [ResourceMethod].
|
||||
pub trait ResourceReadAll: ResourceMethod {
|
||||
/// Handle a GET request on the Resource root.
|
||||
fn read_all(state: State) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
|
||||
}
|
||||
|
||||
/// The read [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The read [ResourceMethod].
|
||||
pub trait ResourceRead: ResourceMethod {
|
||||
/// The ID type to be parsed from the request path.
|
||||
type ID: ResourceID + 'static;
|
||||
|
@ -45,7 +45,7 @@ pub trait ResourceRead: ResourceMethod {
|
|||
fn read(state: State, id: Self::ID) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
|
||||
}
|
||||
|
||||
/// The search [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The search [ResourceMethod].
|
||||
pub trait ResourceSearch: ResourceMethod {
|
||||
/// The Query type to be parsed from the request parameters.
|
||||
type Query: ResourceType + QueryStringExtractor<Body> + Sync;
|
||||
|
@ -54,7 +54,7 @@ pub trait ResourceSearch: ResourceMethod {
|
|||
fn search(state: State, query: Self::Query) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
|
||||
}
|
||||
|
||||
/// The create [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The create [ResourceMethod].
|
||||
pub trait ResourceCreate: ResourceMethod {
|
||||
/// The Body type to be parsed from the request body.
|
||||
type Body: RequestBody;
|
||||
|
@ -63,7 +63,7 @@ pub trait ResourceCreate: ResourceMethod {
|
|||
fn create(state: State, body: Self::Body) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
|
||||
}
|
||||
|
||||
/// The change_all [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The change_all [ResourceMethod].
|
||||
pub trait ResourceChangeAll: ResourceMethod {
|
||||
/// The Body type to be parsed from the request body.
|
||||
type Body: RequestBody;
|
||||
|
@ -72,7 +72,7 @@ pub trait ResourceChangeAll: ResourceMethod {
|
|||
fn change_all(state: State, body: Self::Body) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
|
||||
}
|
||||
|
||||
/// The change [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The change [ResourceMethod].
|
||||
pub trait ResourceChange: ResourceMethod {
|
||||
/// The Body type to be parsed from the request body.
|
||||
type Body: RequestBody;
|
||||
|
@ -83,13 +83,13 @@ pub trait ResourceChange: ResourceMethod {
|
|||
fn change(state: State, id: Self::ID, body: Self::Body) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
|
||||
}
|
||||
|
||||
/// The remove_all [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The remove_all [ResourceMethod].
|
||||
pub trait ResourceRemoveAll: ResourceMethod {
|
||||
/// Handle a DELETE request on the Resource root.
|
||||
fn remove_all(state: State) -> Pin<Box<dyn Future<Output = (State, Self::Res)> + Send>>;
|
||||
}
|
||||
|
||||
/// The remove [`ResourceMethod`](trait.ResourceMethod.html).
|
||||
/// The remove [ResourceMethod].
|
||||
pub trait ResourceRemove: ResourceMethod {
|
||||
/// The ID type to be parsed from the request path.
|
||||
type ID: ResourceID + 'static;
|
||||
|
|
|
@ -10,7 +10,7 @@ pub struct Response {
|
|||
}
|
||||
|
||||
impl Response {
|
||||
/// Create a new `Response` from raw data.
|
||||
/// Create a new [Response] from raw data.
|
||||
pub fn new<B: Into<Body>>(status: StatusCode, body: B, mime: Option<Mime>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
|
@ -19,7 +19,7 @@ impl Response {
|
|||
}
|
||||
}
|
||||
|
||||
/// Create a `Response` with mime type json from already serialized data.
|
||||
/// Create a [Response] with mime type json from already serialized data.
|
||||
pub fn json<B: Into<Body>>(status: StatusCode, body: B) -> Self {
|
||||
Self {
|
||||
status,
|
||||
|
@ -28,7 +28,7 @@ impl Response {
|
|||
}
|
||||
}
|
||||
|
||||
/// Create a _204 No Content_ `Response`.
|
||||
/// Create a _204 No Content_ [Response].
|
||||
pub fn no_content() -> Self {
|
||||
Self {
|
||||
status: StatusCode::NO_CONTENT,
|
||||
|
@ -37,7 +37,7 @@ impl Response {
|
|||
}
|
||||
}
|
||||
|
||||
/// Create an empty _403 Forbidden_ `Response`.
|
||||
/// Create an empty _403 Forbidden_ [Response].
|
||||
pub fn forbidden() -> Self {
|
||||
Self {
|
||||
status: StatusCode::FORBIDDEN,
|
||||
|
|
|
@ -2,10 +2,7 @@ use gotham_restful_derive::ResourceError;
|
|||
|
||||
/**
|
||||
This is an error type that always yields a _403 Forbidden_ response. This type is best used in
|
||||
combination with [`AuthSuccess`] or [`AuthResult`].
|
||||
|
||||
[`AuthSuccess`]: type.AuthSuccess.html
|
||||
[`AuthResult`]: type.AuthResult.html
|
||||
combination with [AuthSuccess] or [AuthResult].
|
||||
*/
|
||||
#[derive(Debug, Clone, Copy, ResourceError)]
|
||||
pub enum AuthError {
|
||||
|
@ -15,9 +12,11 @@ pub enum AuthError {
|
|||
}
|
||||
|
||||
/**
|
||||
This return type can be used to map another `ResourceResult` that can only be returned if the
|
||||
client is authenticated. Otherwise, an empty _403 Forbidden_ response will be issued. Use can
|
||||
look something like this (assuming the `auth` feature is enabled):
|
||||
This return type can be used to map another [ResourceResult](crate::ResourceResult) that can
|
||||
only be returned if the client is authenticated. Otherwise, an empty _403 Forbidden_ response
|
||||
will be issued.
|
||||
|
||||
Use can look something like this (assuming the `auth` feature is enabled):
|
||||
|
||||
```rust
|
||||
# #[macro_use] extern crate gotham_restful_derive;
|
||||
|
@ -50,9 +49,7 @@ pub type AuthSuccess<T> = Result<T, AuthError>;
|
|||
|
||||
/**
|
||||
This is an error type that either yields a _403 Forbidden_ respone if produced from an authentication
|
||||
error, or delegates to another error type. This type is best used with [`AuthResult`].
|
||||
|
||||
[`AuthResult`]: type.AuthResult.html
|
||||
error, or delegates to another error type. This type is best used with [AuthResult].
|
||||
*/
|
||||
#[derive(Debug, ResourceError)]
|
||||
pub enum AuthErrorOrOther<E> {
|
||||
|
@ -83,9 +80,11 @@ where
|
|||
}
|
||||
|
||||
/**
|
||||
This return type can be used to map another `ResourceResult` that can only be returned if the
|
||||
client is authenticated. Otherwise, an empty _403 Forbidden_ response will be issued. Use can
|
||||
look something like this (assuming the `auth` feature is enabled):
|
||||
This return type can be used to map another [ResourceResult](crate::ResourceResult) that can
|
||||
only be returned if the client is authenticated. Otherwise, an empty _403 Forbidden_ response
|
||||
will be issued.
|
||||
|
||||
Use can look something like this (assuming the `auth` feature is enabled):
|
||||
|
||||
```
|
||||
# #[macro_use] extern crate gotham_restful_derive;
|
||||
|
|
|
@ -14,7 +14,7 @@ use std::{convert::Infallible, fmt::Display, pin::Pin};
|
|||
/**
|
||||
This type can be used both as a raw request body, as well as as a raw response. However, all types
|
||||
of request bodies are accepted by this type. It is therefore recommended to derive your own type
|
||||
from [`RequestBody`] and only use this when you need to return a raw response. This is a usage
|
||||
from [RequestBody] and only use this when you need to return a raw response. This is a usage
|
||||
example that simply returns its body:
|
||||
|
||||
```rust,no_run
|
||||
|
@ -35,8 +35,6 @@ fn create(body : Raw<Vec<u8>>) -> Raw<Vec<u8>> {
|
|||
# }));
|
||||
# }
|
||||
```
|
||||
|
||||
[`OpenapiType`]: trait.OpenapiType.html
|
||||
*/
|
||||
#[derive(Debug)]
|
||||
pub struct Raw<T> {
|
||||
|
|
|
@ -13,7 +13,7 @@ use std::{
|
|||
|
||||
/**
|
||||
This can be returned from a resource when there is no cause of an error. It behaves similar to a
|
||||
smart pointer like box, it that it implements `AsRef`, `Deref` and the likes.
|
||||
smart pointer like box, it that it implements [AsRef], [Deref] and the likes.
|
||||
|
||||
Usage example:
|
||||
|
||||
|
|
|
@ -44,13 +44,13 @@ pub trait WithOpenapi<D> {
|
|||
}
|
||||
|
||||
/// This trait adds the `resource` method to gotham's routing. It allows you to register
|
||||
/// any RESTful `Resource` with a path.
|
||||
/// any RESTful [Resource] with a path.
|
||||
pub trait DrawResources {
|
||||
fn resource<R: Resource>(&mut self, path: &str);
|
||||
}
|
||||
|
||||
/// This trait allows to draw routes within an resource. Use this only inside the
|
||||
/// `Resource::setup` method.
|
||||
/// [Resource::setup] method.
|
||||
pub trait DrawResourceRoutes {
|
||||
fn read_all<Handler: ResourceReadAll>(&mut self);
|
||||
|
||||
|
|
33
src/types.rs
33
src/types.rs
|
@ -20,18 +20,21 @@ impl<T: OpenapiType> ResourceType for T {}
|
|||
|
||||
/// A type that can be used inside a response body. Implemented for every type that is
|
||||
/// serializable with serde. If the `openapi` feature is used, it must also be of type
|
||||
/// `OpenapiType`.
|
||||
/// [OpenapiType].
|
||||
///
|
||||
/// [OpenapiType]: trait.OpenapiType.html
|
||||
pub trait ResponseBody: ResourceType + Serialize {}
|
||||
|
||||
impl<T: ResourceType + Serialize> ResponseBody for T {}
|
||||
|
||||
/**
|
||||
This trait should be implemented for every type that can be built from an HTTP request body
|
||||
plus its media type. For most use cases it is sufficient to derive this trait, you usually
|
||||
don't need to manually implement this. Therefore, make sure that the first variable of
|
||||
your struct can be built from [`Bytes`], and the second one can be build from [`Mime`].
|
||||
If you have any additional variables, they need to be `Default`. This is an example of
|
||||
such a struct:
|
||||
plus its media type.
|
||||
|
||||
For most use cases it is sufficient to derive this trait, you usually don't need to manually
|
||||
implement this. Therefore, make sure that the first variable of your struct can be built from
|
||||
[Bytes], and the second one can be build from [Mime]. If you have any additional variables, they
|
||||
need to be [Default]. This is an example of such a struct:
|
||||
|
||||
```rust
|
||||
# #[macro_use] extern crate gotham_restful;
|
||||
|
@ -43,14 +46,11 @@ struct RawImage {
|
|||
content_type: Mime
|
||||
}
|
||||
```
|
||||
|
||||
[`Bytes`]: ../bytes/struct.Bytes.html
|
||||
[`Mime`]: ../mime/struct.Mime.html
|
||||
*/
|
||||
pub trait FromBody: Sized {
|
||||
/// The error type returned by the conversion if it was unsuccessfull. When using the derive
|
||||
/// macro, there is no way to trigger an error, so `Infallible` is used here. However, this
|
||||
/// might change in the future.
|
||||
/// macro, there is no way to trigger an error, so [std::convert::Infallible] is used here.
|
||||
/// However, this might change in the future.
|
||||
type Err: Error;
|
||||
|
||||
/// Perform the conversion.
|
||||
|
@ -67,11 +67,11 @@ impl<T: DeserializeOwned> FromBody for T {
|
|||
|
||||
/**
|
||||
A type that can be used inside a request body. Implemented for every type that is deserializable
|
||||
with serde. If the `openapi` feature is used, it must also be of type [`OpenapiType`].
|
||||
with serde. If the `openapi` feature is used, it must also be of type [OpenapiType].
|
||||
|
||||
If you want a non-deserializable type to be used as a request body, e.g. because you'd like to
|
||||
get the raw data, you can derive it for your own type. All you need is to have a type implementing
|
||||
[`FromBody`] and optionally a list of supported media types:
|
||||
[FromBody] and optionally a list of supported media types:
|
||||
|
||||
```rust
|
||||
# #[macro_use] extern crate gotham_restful;
|
||||
|
@ -84,8 +84,7 @@ struct RawImage {
|
|||
}
|
||||
```
|
||||
|
||||
[`FromBody`]: trait.FromBody.html
|
||||
[`OpenapiType`]: trait.OpenapiType.html
|
||||
[OpenapiType]: trait.OpenapiType.html
|
||||
*/
|
||||
pub trait RequestBody: ResourceType + FromBody {
|
||||
/// Return all types that are supported as content types. Use `None` if all types are supported.
|
||||
|
@ -102,7 +101,9 @@ impl<T: ResourceType + DeserializeOwned> RequestBody for T {
|
|||
|
||||
/// A type than can be used as a parameter to a resource method. Implemented for every type
|
||||
/// that is deserialize and thread-safe. If the `openapi` feature is used, it must also be of
|
||||
/// type `OpenapiType`.
|
||||
/// type [OpenapiType].
|
||||
///
|
||||
/// [OpenapiType]: trait.OpenapiType.html
|
||||
pub trait ResourceID: ResourceType + DeserializeOwned + Clone + RefUnwindSafe + Send + Sync {}
|
||||
|
||||
impl<T: ResourceType + DeserializeOwned + Clone + RefUnwindSafe + Send + Sync> ResourceID for T {}
|
||||
|
|
Loading…
Add table
Reference in a new issue