use super::*;
impl FieldSelection {
#[inline]
pub fn response_key(&self) -> &str {
let Self { alias, name, .. } = self;
match alias {
Some(a) => a.as_str(),
None => name.as_str(),
}
}
}
impl GraphqlFieldArgs {
#[inline]
pub fn arg(&self, name: &str) -> Option<&Value> {
self.get_arguments().get(name)
}
#[inline]
pub fn arg_str(&self, name: &str) -> Option<&str> {
self.arg(name).and_then(Value::as_str)
}
#[inline]
pub fn arg_i64(&self, name: &str) -> Option<i64> {
self.arg(name).and_then(Value::as_i64)
}
}
impl<F> GraphqlResolver for FnGraphqlResolver<F>
where
F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
{
fn resolve(&self, args: &GraphqlFieldArgs) -> Result<Value, String> {
let Self { func } = self;
func(args)
}
}
impl GraphqlResponse {
pub fn from_error<S>(message: S) -> Self
where
S: Into<String>,
{
Self {
data: None,
errors: vec![GraphqlError {
message: message.into(),
}],
}
}
}
impl Default for GraphqlConfig {
fn default() -> Self {
Self {
endpoint: DEFAULT_GRAPHQL_ENDPOINT.to_owned(),
max_depth: DEFAULT_MAX_DEPTH,
max_fields: DEFAULT_MAX_FIELDS,
max_query_bytes: DEFAULT_MAX_QUERY_BYTES,
allow_get: true,
}
}
}
impl GraphqlConfig {
pub fn with_endpoint<S>(mut self, endpoint: S) -> Self
where
S: Into<String>,
{
self.set_endpoint(endpoint.into());
self
}
pub fn with_max_depth(mut self, max_depth: usize) -> Self {
self.set_max_depth(max_depth.max(1));
self
}
pub fn with_max_fields(mut self, max_fields: usize) -> Self {
self.set_max_fields(max_fields.max(1));
self
}
}
impl GraphqlPlugin {
pub fn new(config: GraphqlConfig) -> Self {
Self {
config,
queries: hash_map_xx_hash3_64(),
mutations: hash_map_xx_hash3_64(),
}
}
pub fn with_query<N, F>(mut self, field_name: N, resolver: F) -> Self
where
N: Into<String>,
F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
{
let Self { queries, .. } = &mut self;
let _: Option<Arc<dyn GraphqlResolver>> = queries.insert(
field_name.into(),
Arc::new(FnGraphqlResolver { func: resolver }),
);
self
}
pub fn with_mutation<N, F>(mut self, field_name: N, resolver: F) -> Self
where
N: Into<String>,
F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
{
let Self { mutations, .. } = &mut self;
let _: Option<Arc<dyn GraphqlResolver>> = mutations.insert(
field_name.into(),
Arc::new(FnGraphqlResolver { func: resolver }),
);
self
}
pub fn init(plugin: Self) -> &'static Self {
GRAPHQL_PLUGIN.get_or_init(|| plugin)
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
GRAPHQL_PLUGIN.get()
}
#[inline(always)]
pub fn endpoint(&self) -> &str {
let Self { config, .. } = self;
config.get_endpoint().as_str()
}
pub fn execute(&self, req: &GraphqlRequest, allow_mutation: bool) -> GraphqlResponse {
let Self {
config,
queries,
mutations,
..
} = self;
if req.get_query().len() > config.get_max_query_bytes() {
return GraphqlResponse::from_error(ERR_QUERY_TOO_LARGE);
}
let op: ParsedOperation = match parse_graphql_document(
req.get_query(),
req.get_variables(),
config.get_max_depth(),
config.get_max_fields(),
) {
Ok(parsed) => parsed,
Err(err) => return GraphqlResponse::from_error(err),
};
if op.get_kind() == OperationKind::Mutation && !allow_mutation {
return GraphqlResponse::from_error(ERR_GET_MUTATION);
}
let registry: &HashMapXxHash3_64<String, Arc<dyn GraphqlResolver>> = match op.get_kind() {
OperationKind::Query => queries,
OperationKind::Mutation => mutations,
};
let mut data_map: Map<String, Value> = Map::with_capacity(op.get_selections().len());
let mut errors: Vec<GraphqlError> = Vec::new();
for sel in op.get_selections() {
let out_key: String = sel.response_key().to_owned();
if let Some(resolver) = registry.get(sel.get_name()) {
let args: GraphqlFieldArgs = GraphqlFieldArgs {
arguments: sel.get_arguments().clone(),
variables: req.get_variables().clone(),
};
match resolver.resolve(&args) {
Ok(val) => {
let projected: Value = project_selection(val, sel.get_sub_fields());
let _: Option<Value> = data_map.insert(out_key, projected);
}
Err(msg) => {
let _: Option<Value> = data_map.insert(out_key, Value::Null);
errors.push(GraphqlError { message: msg });
}
}
} else {
let _: Option<Value> = data_map.insert(out_key, Value::Null);
errors.push(GraphqlError {
message: format!("unknown GraphQL field: {}", sel.get_name()),
});
}
}
GraphqlResponse {
data: Some(Value::Object(data_map)),
errors,
}
}
pub fn handle_http_request(&self, request: &Request) -> (HttpStatus, Vec<u8>) {
let Self { config, .. } = self;
let method: &Method = request.get_method();
if method.is_post() {
let gql_req: GraphqlRequest = match from_slice(request.get_body()) {
Ok(parsed) => parsed,
Err(_) => {
let err: GraphqlResponse = GraphqlResponse::from_error(ERR_INVALID_JSON);
return (HttpStatus::BadRequest, to_vec(&err).unwrap_or_default());
}
};
let resp: GraphqlResponse = self.execute(&gql_req, true);
(HttpStatus::Ok, to_vec(&resp).unwrap_or_default())
} else if method.is_get() && config.get_allow_get() {
let Some(query_val) = request
.try_get_query(QUERY_PARAM_KEY)
.and_then(|vals: VecDeque<String>| vals.into_iter().next())
else {
let err: GraphqlResponse = GraphqlResponse::from_error(ERR_MISSING_QUERY);
return (HttpStatus::BadRequest, to_vec(&err).unwrap_or_default());
};
let gql_req: GraphqlRequest = GraphqlRequest {
query: query_val,
operation_name: None,
variables: Map::new(),
};
let resp: GraphqlResponse = self.execute(&gql_req, false);
(HttpStatus::Ok, to_vec(&resp).unwrap_or_default())
} else {
let err: GraphqlResponse = GraphqlResponse::from_error(ERR_METHOD_NOT_ALLOWED);
(
HttpStatus::MethodNotAllowed,
to_vec(&err).unwrap_or_default(),
)
}
}
}
impl ServerHook for GraphqlHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = GraphqlPlugin::get() else {
return Status::Continue;
};
if ctx.get_request().get_path() != plugin.endpoint() {
return Status::Continue;
}
let (status, body): (HttpStatus, Vec<u8>) = plugin.handle_http_request(ctx.get_request());
ctx.get_mut_response()
.set_status_code(status.code())
.set_header(CONTENT_TYPE, GRAPHQL_JSON_CONTENT_TYPE)
.set_body(body);
let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
Status::Reject
}
}