Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
GraphQL.hpp
Go to the documentation of this file.
1#pragma once
6#include <functional>
7#include <string>
8#include <orbit/http/json.hpp>
9
10namespace orbit::middleware {
11
17using GraphQLExecutor = std::function<nlohmann::json(const std::string& query, const std::string& operation_name, const nlohmann::json& variables)>;
18
26inline std::function<bool(http::HttpRequest&, std::shared_ptr<http::ResponseWriter>)> graphql(GraphQLExecutor executor) {
27 return [executor](http::HttpRequest& req, std::shared_ptr<http::ResponseWriter> res) -> bool {
28 std::string query;
29 std::string operation_name;
31
32 if (req.method == http::HttpMethod::POST) {
33 if (req.headers.count("Content-Type") && req.headers.at("Content-Type").find("application/json") != std::string::npos) {
34 auto body = req.json();
35 if (body.contains("query") && body["query"].is_string()) {
36 query = body["query"].get<std::string>();
37 }
38 if (body.contains("operationName") && body["operationName"].is_string()) {
39 operation_name = body["operationName"].get<std::string>();
40 }
41 if (body.contains("variables") && body["variables"].is_object()) {
42 variables = body["variables"];
43 }
44 } else if (req.headers.count("Content-Type") && req.headers.at("Content-Type").find("application/graphql") != std::string::npos) {
45 query = req.body;
46 }
47 } else if (req.method == http::HttpMethod::GET) {
48 // Parse from URL parameters
49 auto it_query = req.query.find("query");
50 if (it_query != req.query.end()) query = it_query->second;
51
52 auto it_op = req.query.find("operationName");
53 if (it_op != req.query.end()) operation_name = it_op->second;
54
55 auto it_vars = req.query.find("variables");
56 if (it_vars != req.query.end()) {
57 try {
58 variables = nlohmann::json::parse(it_vars->second);
59 } catch (...) {
60 // Ignore or handle invalid JSON variables in GET
61 }
62 }
63 }
64
65 if (query.empty()) {
66 http::HttpResponse response;
68 response.json(nlohmann::json{{"errors", nlohmann::json::array({{{"message", "GraphQL query is missing"}}})}});
69 res->send(std::move(response));
70 return false;
71 }
72
73 try {
74 nlohmann::json result = executor(query, operation_name, variables);
75 http::HttpResponse response;
77 response.json(result);
78 res->send(std::move(response));
79 } catch (const std::exception& e) {
80 http::HttpResponse response;
82 // Built as JSON, never by concatenation: a message with a quote,
83 // backslash or newline used to produce an invalid body (#188).
84 response.json(nlohmann::json{{"errors", nlohmann::json::array({{{"message", e.what()}}})}});
85 res->send(std::move(response));
86 }
87
88 return false; // Stop middleware chain, response sent
89 };
90}
91
92} // namespace middleware
a class to store JSON values
Definition json.hpp:19401
static basic_json parse(InputType &&i, const parser_callback_t cb=nullptr, const bool allow_exceptions=true, const bool ignore_comments=false)
deserialize from a compatible input
Definition json.hpp:23317
auto get() const noexcept(noexcept(std::declval< const basic_json_t & >().template get_impl< ValueType >(detail::priority_tag< 4 > {}))) -> decltype(std::declval< const basic_json_t & >().template get_impl< ValueType >(detail::priority_tag< 4 > {}))
get a (pointer) value (explicit)
Definition json.hpp:21046
static basic_json array(initializer_list_t init={})
explicitly create an array from an initializer list
Definition json.hpp:20307
static basic_json object(initializer_list_t init={})
explicitly create an object from an initializer list
Definition json.hpp:20315
Represents an HTTP response to be sent to a client.
Definition HttpResponse.hpp:107
HttpResponse & json(const std::string &j) &
Sets the response body as JSON from a string.
Definition HttpResponse.hpp:181
HttpStatus status_code
Definition HttpResponse.hpp:110
HttpResponse & send(const std::string &b) &
Sets the response body as plain text.
Definition HttpResponse.hpp:174
basic_json<> json
default specialization
Definition json.hpp:3422
Definition HttpRequest.hpp:19
std::function< bool(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> graphql(GraphQLExecutor executor)
Creates a middleware handler for GraphQL endpoints. It parses the incoming GET or POST request accord...
Definition GraphQL.hpp:26
std::function< nlohmann::json(const std::string &query, const std::string &operation_name, const nlohmann::json &variables)> GraphQLExecutor
Signature for a GraphQL executor function. Takes the query string, operation name (optional),...
Definition GraphQL.hpp:17
Represents an incoming HTTP request.
Definition HttpRequest.hpp:54
HttpMethod method
Definition HttpRequest.hpp:55
std::unordered_map< std::string, std::string > query
Definition HttpRequest.hpp:58
nlohmann::json json() const
Parses and returns the request body as a JSON object.
Definition HttpRequest.hpp:150
std::string_view body
Definition HttpRequest.hpp:61
std::unordered_map< std::string_view, std::string_view, utils::CaseInsensitiveHash, utils::CaseInsensitiveEqual > headers
Definition HttpRequest.hpp:60