我应该以 { "data":{ ... } } 的形式接收对 api 的请求。我经常需要从数据中获取所有必要的信息。在请求主体沿着路线进一步前进之前,我怎样才能做到这一点?
#[derive(Debug, Deserialize)]
pub struct ApiData<T> {
pub data: T,
}
struct ExtractData;
#[rocket::async_trait]
impl<T> Fairing for ExtractData
where
T: FromRequest<'static>,
{
fn info(&self) -> Info {
Info {
name: "ExtractData",
kind: Kind::Request,
}
}
async fn on_request<'a>(&self, req: &'a mut Request<'_>, _: &'a Data<'_>) {
if let Some(data) = req.guard::<ApiData<T>>().succeeded() {
req.local_cache(|| data.data);
} else {
req.set_abort(Some(Status::BadRequest));
}
}
}
#[launch]
async fn rocket() -> _ {
let db = MongoRepo::init().await;
rocket::build().manage(db)
.attach(ExtractData)
.mount("/api/", routes![get_files_in_directories])
.mount("/api/usepi/patterns", routes![create_pattern])
.mount(
"/api/usepi/patterns/icons",
FileServer::from(Path::new("./src/icons")),
)
}
我正在尝试以这种方式实现它,但总是存在类型错误
error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
--> src/main.rs:54:6
|
54 | impl<T> Fairing for ExtractData
| ^ unconstrained type parameter
我不知道该怎么做,请告诉我