Make `Schema::execute` return HTTP headers when an error occurs. #572

This commit is contained in:
Sunli 2021-07-16 07:47:43 +08:00
parent 7b9942ef10
commit 8f8fe3e46d
2 changed files with 29 additions and 3 deletions

View File

@ -479,10 +479,10 @@ where
};
let mut resp = match res {
Ok(value) => Response::new(value)
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap())),
Ok(value) => Response::new(value),
Err(err) => Response::from_errors(vec![err]),
};
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));

View File

@ -16,3 +16,29 @@ pub async fn test_schema_default() {
let _schema = MySchema::default();
}
#[tokio::test]
pub async fn test_http_headers() {
#[derive(Default)]
struct QueryRoot;
#[Object]
impl QueryRoot {
async fn value(&self, ctx: &Context<'_>) -> i32 {
ctx.insert_http_header("A", "1");
10
}
async fn err(&self, ctx: &Context<'_>) -> FieldResult<i32> {
ctx.insert_http_header("A", "1");
Err("error".into())
}
}
let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription);
let resp = schema.execute("{ value }").await;
assert_eq!(resp.http_headers.get("A").map(|s| &**s), Some("1"));
let resp = schema.execute("{ err }").await;
assert_eq!(resp.http_headers.get("A").map(|s| &**s), Some("1"));
}