Skip to main content

Operation

Struct Operation 

Source
pub struct Operation { /* private fields */ }
Expand description

Describes a route in the API document.

Add it to a route with with(...). A route appears in the document when an Operation is attached to it or to a layer that wraps it:

use serde::{Deserialize, Serialize};
use topcoat::{
    Result,
    context::Cx,
    openapi::{Operation, schemars::JsonSchema},
    router::{Body, Next, StatusCode, content::Json, layer, response::Response, route},
};

#[derive(Deserialize, JsonSchema)]
struct CreateUser {
    name: String,
}

#[derive(Serialize, JsonSchema)]
struct User {
    id: u64,
    name: String,
}

// Every route under `/api` is documented and tagged.
#[layer("/api", with(Operation::new().tag("api")))]
async fn api(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
    next.run(cx, body).await
}

#[route(POST "/api/users", with(
    Operation::new()
        .summary("Create a user")
        .request::<Json<CreateUser>>()
        .response_with::<Json<User>>(StatusCode::CREATED, "The new user.")
))]
async fn create_user(
    cx: &Cx,
    Json(input): Json<CreateUser>,
) -> Result<(StatusCode, Json<User>)> {
    Ok((
        StatusCode::CREATED,
        Json(User {
            id: 1,
            name: input.name,
        }),
    ))
}

A route combines its own operation with those of its layers, and the closest value of each setting takes priority. Tags, parameters, and responses add up instead: a route keeps the ones its layers declare and replaces only a parameter or response status it declares itself.

Implementations§

Source§

impl Operation

Source

pub fn new() -> Self

Creates an operation that inherits every setting.

Source

pub fn summary(self, summary: impl Into<Cow<'static, str>>) -> Self

Sets a short summary of what the route does.

Source

pub fn description(self, description: impl Into<Cow<'static, str>>) -> Self

Sets a longer explanation of the route’s behavior.

Source

pub fn operation_id(self, operation_id: impl Into<Cow<'static, str>>) -> Self

Sets the name that identifies the operation, which client generators use to name their functions.

An ID has to be unique in the document, so set it on a route that serves a single method rather than on a layer.

Source

pub fn deprecated(self, deprecated: bool) -> Self

Marks the route as deprecated, so clients know to move away from it.

Source

pub fn hidden(self, hidden: bool) -> Self

Chooses whether to leave the route out of the document.

Pass true to hide a route that a layer documents. Pass false to show a route below a layer that hides its routes.

Source

pub fn tag(self, tag: impl Into<Cow<'static, str>>) -> Self

Adds a tag, which documentation tools use to group routes.

Source

pub fn parameter(self, parameter: Parameter) -> Self

Describes a path, query, header, or cookie parameter.

Describing the same parameter again replaces the earlier entry.

Source

pub fn query<T: JsonSchema>(self) -> Self

Documents every field of the struct T as a query parameter.

This suits a struct read with query_params. Optional fields become optional parameters, and doc comments on fields become their descriptions:

use topcoat::{
    openapi::{Operation, schemars::JsonSchema},
    router::query_params,
};

#[query_params]
#[derive(JsonSchema)]
struct PostsQuery {
    /// The page to show, starting at 1.
    page: Option<u32>,
}

let operation = Operation::new().query::<PostsQuery>();
Source

pub fn request<T: Content>(self) -> Self

Documents the request body, for example .request::<Json<CreateUser>>().

Wrap the type in Option for a body that requests may leave out.

Source

pub fn response( self, status: StatusCode, description: impl Into<Cow<'static, str>>, ) -> Self

Documents a response without a body, for example .response(StatusCode::NO_CONTENT, "The user was deleted.").

Declaring a status again replaces its earlier response.

Source

pub fn response_with<T: Content>( self, status: StatusCode, description: impl Into<Cow<'static, str>>, ) -> Self

Documents a response with a body, for example .response_with::<Json<User>>(StatusCode::OK, "The user.").

Declaring a status again replaces its earlier response.

Source

pub fn security(self, scheme: impl Into<Cow<'static, str>>) -> Self

Requires clients to authenticate with the security scheme registered under scheme.

Calling this again adds an alternative, so clients may use either scheme. The requirements of an operation replace those of its layers as a whole.

See OpenApi::security_scheme for registering a scheme.

Source

pub fn no_security(self) -> Self

Documents the route as usable without authentication, even when a layer requires it.

Trait Implementations§

Source§

impl Clone for Operation

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Operation

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Operation

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.