Skip to main content

mockql_core/upstream/
http.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! HTTP helpers for executing upstream GraphQL requests.
16
17use crate::Header;
18use crate::graphql::GraphQLResponse;
19use reqwest::StatusCode;
20use reqwest::Url;
21use reqwest::header::HeaderMap;
22use serde_json::json;
23use serde_json_bytes::ByteString;
24use serde_json_bytes::Map;
25use serde_json_bytes::Value;
26use thiserror::Error;
27
28/// Errors raised while building or executing upstream GraphQL requests.
29#[derive(Debug, Error)]
30pub enum UpstreamError {
31  /// The upstream HTTP request failed before a response could be received.
32  #[error("upstream request failed: {0}")]
33  Request(#[source] reqwest::Error),
34  /// The upstream server returned a non-success HTTP status.
35  #[error("upstream request returned HTTP status: {status}, body: {body}")]
36  HttpStatus {
37    /// HTTP status code returned by the upstream server.
38    status: StatusCode,
39    /// Response body returned alongside the HTTP status.
40    body: String,
41  },
42  /// The upstream response body was not valid GraphQL JSON.
43  #[error("upstream returned invalid JSON: {0}")]
44  InvalidJson(#[source] serde_json::Error),
45}
46
47/// Executes a GraphQL operation against an upstream endpoint.
48pub async fn execute_graphql(
49  client: &reqwest::Client,
50  url: Url,
51  headers: &[Header],
52  operation: &str,
53  operation_name: Option<&str>,
54  variables: &Map<ByteString, Value>,
55) -> Result<GraphQLResponse, UpstreamError> {
56  let response = client
57    .post(url)
58    .headers(headers.iter().cloned().collect::<HeaderMap>())
59    .json(&json!({
60      "query": operation,
61      "operationName": operation_name,
62      "variables": variables,
63    }))
64    .send()
65    .await
66    .map_err(UpstreamError::Request)?;
67
68  let status = response.status();
69  if !status.is_success() {
70    let body = response.text().await.unwrap_or_default();
71    return Err(UpstreamError::HttpStatus { status, body });
72  }
73
74  let body: serde_json::Value = response.json().await.map_err(UpstreamError::Request)?;
75  GraphQLResponse::try_from(body).map_err(UpstreamError::InvalidJson)
76}