Comments (3)
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.
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.
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)
- Supply PanicInfo to Catchers where applicable HOT 2
- (Solved) Rocket database fairing panicking while connecting to dockerized postgres on MacOS Sonoma HOT 1
- Responder enums not serializing like expected HOT 1
- FileServer can serve pre-gzipped content if it exists on the filesystem HOT 1
- Cookies aren't read by get methods but it exists in the browser HOT 2
- HTTP3/QUIC support HOT 15
- Add HTMLStream HOT 5
- cookie removal and Microsoft Edge HOT 7
- Inject script to auto-reload browser when Rocket restarts HOT 1
- Rocket App Hangs HOT 5
- DefaultListener::bindable() isnβt usable HOT 8
- Allow routes that match any method HOT 4
- Hyper and Rocket disagreeing on validity of URL HOT 3
- Allow from form macro to work on structs with range HOT 4
- Clippy Lint w/ FromForm derive HOT 7
- Possible Incompleteness HOT 1
- Possible Incompleteness HOT 1
- doc: change `&ContentType` with `&Accept` in the list of implementations of `FromRequest` HOT 1
- [Feature]: Enhanced State Mutation for Effortless Handling of Shared Resources HOT 5
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from rocket.