GREsau / okapi

OpenAPI (AKA Swagger) document generation for Rust projects
MIT License
631 stars 112 forks source link

How to document handlers with rocket_oauth2 structs #140

Closed kotsmile closed 8 months ago

kotsmile commented 9 months ago

I have

#[get("/login/google")]
pub fn get_login_google(oauth2: OAuth2<GoogleUserInfo>, cookies: &CookieJar<'_>) -> Redirect {
    oauth2
        .get_redirect(cookies, &["https://www.googleapis.com/auth/userinfo.email"])
        .unwrap()
}

But i cant wrap it in my custom struct, because it is Guard

How to add openapi docs?

kotsmile commented 8 months ago

Need to write wrapper with zero doc

pub struct GhostOpenApiDoc<T>(T);

impl<T> GhostOpenApiDoc<T> {
    pub fn into_inner(&self) -> &T {
        &self.0
    }
}

#[async_trait()]
impl<'r, T: FromRequest<'r>> FromRequest<'r> for GhostOpenApiDoc<T> {
    type Error = T::Error;
    async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
        match T::from_request(request).await {
            request::Outcome::Success(o) => request::Outcome::Success(GhostOpenApiDoc(o)),
            request::Outcome::Error(o) => request::Outcome::Error(o),
            request::Outcome::Forward(o) => request::Outcome::Forward(o),
        }
    }
}

impl<'r, T: FromRequest<'r>> OpenApiFromRequest<'r> for GhostOpenApiDoc<T> {
    fn from_request_input(
        _gen: &mut rocket_okapi::gen::OpenApiGenerator,
        _name: String,
        _required: bool,
    ) -> rocket_okapi::Result<rocket_okapi::request::RequestHeaderInput> {
        rocket_okapi::Result::Ok(rocket_okapi::request::RequestHeaderInput::None)
    }

    fn get_responses(
        _gen: &mut rocket_okapi::gen::OpenApiGenerator,
    ) -> rocket_okapi::Result<rocket_okapi::okapi::openapi3::Responses> {
        Ok(rocket_okapi::okapi::openapi3::Responses::default())
    }
}

#[openapi(tag = "Auth")]
#[get("/auth/login/google")]
pub fn get_login_google(
    oauth2: GhostOpenApiDoc<OAuth2<GoogleUserInfo>>,
    cookies: &CookieJar<'_>,
) -> Redirect {
    oauth2
        .into_inner()
        .get_redirect(cookies, &["https://www.googleapis.com/auth/userinfo.email"])
        .unwrap()
}