Skip to content

Commit

Permalink
Validate variables to make sure they are a JSON object as expected.
Browse files Browse the repository at this point in the history
The GraphQL gem internally raises an exception when given variables that are a string:

```
Query variables should be a Hash, not a String. Try JSON.parse to prepare variables.
```

This avoids that exception and returns a friendly 400 error when the client passes `variables`
that are not an object as expected.
  • Loading branch information
myronmarston committed Dec 1, 2024
1 parent 15594ee commit d0e5a51
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ def with_request_params(request)
# Ignore an empty string operationName.
params = params.merge("operationName" => nil) if params["operationName"] && params["operationName"].empty?

if (variables = params["variables"]) && !variables.is_a?(::Hash)
return HTTPResponse.error(400, "Variables must be a JSON object but were not.")
end

yield params
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,13 @@ def with_context(request)
expect(datastore_queries.size).to eq(1)
expect(datastore_queries.first.filters.to_a).to eq [filter]
end

it "returns a 400 response when the variables are not a JSON object" do
query = "query Multiply($operands: Operands!) { multiply(operands: $operands) }"
response = process_graphql_expecting(400, query: query, variables: "not a JSON object")

expect(response).to eq error_with("Variables must be a JSON object but were not.")
end
end

def submitted_value_for(option_name, ...)
Expand Down

0 comments on commit d0e5a51

Please sign in to comment.