Code Monkey home page Code Monkey logo

Comments (3)

SergioBenitez avatar SergioBenitez commented on May 27, 2024 1

The easiest thing to do is this:

type ApiResult<T> = Result<T, Custom<Json<ErrorApiOutput>>>;

#[get("/customers/<customer_id>")]
pub fn get_customer(customer_id: ApiResult<CustomerId>) -> ApiResult<String> {
    let id = customer_id?;
    Ok(id.to_string())
}

from rocket.

mtumilowicz avatar mtumilowicz commented on May 27, 2024

working! thank u very much

@SergioBenitez do u think that we should update documentation? for me connection between FromParam and input type of param in endpoint was not clear

fully working code for ref:

use rocket::{launch};

use rocket::{get, routes};
use rocket::http::{ContentType, Status};
use rocket::local::blocking::Client;
use rocket::request::FromParam;
use rocket::response::status::{Custom};
use rocket::serde::json::{Json, json};
use rocket::serde::uuid::Uuid;
use serde_derive::Serialize;

struct CustomerId(Uuid);

#[derive(Debug, Serialize)]
struct ErrorApiOutput {
    error: String,
}

impl<'r> FromParam<'r> for CustomerId {
    type Error = Custom<Json<ErrorApiOutput>>;

    fn from_param(param: &'r str) -> Result<Self, Self::Error> {
        match Uuid::parse_str(param) {
            Ok(uuid) => Ok(CustomerId(uuid)),
            Err(_) => Err(Custom(Status::UnprocessableEntity, Json(ErrorApiOutput { error: "malformed uuid".to_string() }))),
        }
    }
}

type ApiResult<T> = Result<T, Custom<Json<ErrorApiOutput>>>;

#[get("/customers/<customer_id>")]
pub fn get_customer(customer_id: Result<CustomerId, Custom<Json<ErrorApiOutput>>>) -> Result<String, Custom<Json<ErrorApiOutput>>> {
    let id = customer_id?;
    Ok(id.0.to_string())
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/api", routes![get_customer])
}

#[test] // working
fn test_get_customer_correct_uuid() {
    let client = Client::tracked(rocket()).expect("valid Rocket instance");

    let response = client.get("/api/customers/550e8400-e29b-41d4-a716-446655440000").dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(
        response.into_string(),
        Some("550e8400-e29b-41d4-a716-446655440000".to_string())
    );
}

#[test] // working
fn test_get_customer_incorrect_uuid() {
    let client = Client::tracked(rocket()).expect("valid Rocket instance");

    let response = client.get("/api/customers/invalid-uuid").dispatch();

    assert_eq!(response.status(), Status::UnprocessableEntity);
    assert_eq!(response.content_type(), Some(ContentType::JSON));
    assert_eq!(
        response.into_string(),
        Some(json!({"error": "malformed uuid"}).to_string())
    );
}

from rocket.

SergioBenitez avatar SergioBenitez commented on May 27, 2024

This is already mentioned here: https://rocket.rs/v0.5/guide/requests/#fallible-guards. But I'll keep this in mind for future iteration of the docs.

P.S: You created a type alias that you then don't use. You should use it to clean up the code a bit.

from rocket.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.