我正在用Rust和Warp构建一个graphql api。我查看了文档,但我还没有弄清楚如何链接过滤器,尤其是检查请求标头中的authorization
。
let context_extractor = warp::any()
// this code rejects all request which doesn't contain the authorization in header
// I'd like to make to check if authorization in header
.and(warp::header::<String>("authorization"))
.map(|token: String| -> Context {
let token_data = match verify_jwt(token) {
Ok(t) => t,
Err(_) => return Context { user_id: 0 },
};
Context {
user_id: token_data.claims.user_id,
}
});
let handle_request = move |context: Context,
request: juniper::http::GraphQLRequest|
-> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(&request.execute(&schema, &context))
};
warp::post2()
.and(warp::path(path.into()))
.and(context_extractor)
.and(warp::body::json())
.map(handle_request)
.map(build_response)
.boxed()
这是我的代码部分。它工作正常,但有一个问题。我已经用context_extractor
建立了一条路线.and(warp::header::<String>("authorization")
,然后它拒绝了所有在标题中不包含authorization
的请求。
我该怎么做
authorization
,则返回Context
并使用正确的user_id
Context
一起返回user_id: 0
?我在Warp的github问题中找到了solution。
这是一个小片段。
let context_extractor = warp::any().and(
warp::header::<String>("authorization")
.map(|token: String| -> Context {
let token_data = match verify_jwt(token) {
Ok(t) => t,
Err(_) => return Context { user_id: 0 },
};
Context {
user_id: token_data.claims.user_id,
}
})
.or(warp::any().map(|| Context { user_id: 0 }))
.unify(),
);