ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

GraphQL Argument Validation

GraphQL

Goal -- WPM

Ready
Exercise Algorithm Area
1package graphql;
2
3import java.util.Map;
4import java.util.List;
5import java.util.Set;
6
7public class ArgumentValidator {
8
9// Simplified schema with argument definitions
10private static final Map<String, Map<String, ArgumentDefinition>> ARGUMENT_SCHEMA = Map.of(
11"getUserById", Map.of(
12"id", new ArgumentDefinition(ArgumentType.INT, true, null)
13),
14"getProducts", Map.of(
15"category", new ArgumentDefinition(ArgumentType.STRING, false, "all"),
16"limit", new ArgumentDefinition(ArgumentType.INT, false, 10),
17"isActive", new ArgumentDefinition(ArgumentType.BOOLEAN, false, null)
18),
19"createPost", Map.of(
20"title", new ArgumentDefinition(ArgumentType.STRING, true, null),
21"content", new ArgumentDefinition(ArgumentType.STRING, true, null),
22"tags", new ArgumentDefinition(ArgumentType.STRING, false, null) // Assuming tags are comma-separated string
23)
24);
25
26public static boolean validateArguments(String fieldName, Map<String, Object> arguments) {
27if (!ARGUMENT_SCHEMA.containsKey(fieldName)) {
28// Field not in schema, assume no arguments or handled elsewhere
29return true;
30}
31
32Map<String, ArgumentDefinition> fieldArgs = ARGUMENT_SCHEMA.get(fieldName);
33
34// Check for missing required arguments
35for (Map.Entry<String, ArgumentDefinition> entry : fieldArgs.entrySet()) {
36String argName = entry.getKey();
37ArgumentDefinition argDef = entry.getValue();
38
39if (argDef.isRequired() && !arguments.containsKey(argName)) {
40System.err.println("Validation Error: Missing required argument '" + argName + "' for field '" + fieldName + "'.");
41return false;
42}
43}
44
45// Validate provided arguments
46for (Map.Entry<String, Object> argEntry : arguments.entrySet()) {
47String argName = argEntry.getKey();
48Object argValue = argEntry.getValue();
49
50if (!fieldArgs.containsKey(argName)) {
51System.err.println("Validation Error: Unknown argument '" + argName + "' for field '" + fieldName + "'.");
52return false;
53}
54
55ArgumentDefinition argDef = fieldArgs.get(argName);
56if (!isValidType(argValue, argDef.getType())) {
57System.err.println("Validation Error: Invalid type for argument '" + argName + "' on field '" + fieldName + "'. Expected " + argDef.getType() + ", got " + (argValue == null ? "null" : argValue.getClass().getSimpleName()) + ".");
58return false;
59}
60
61// Additional value checks could be added here (e.g., range, enum values)
62if (argDef.getType() == ArgumentType.INT && argValue != null) {
63int intValue = (Integer) argValue;
64if (argName.equals("limit") && (intValue <= 0 || intValue > 100)) {
65System.err.println("Validation Error: 'limit' argument out of range (1-100) for field '" + fieldName + "'.");
66return false;
67}
68}
69}
70
71return true;
72}
73
74private static boolean isValidType(Object value, ArgumentType expectedType) {
75if (value == null) {
76return true; // Null is generally acceptable if not required
77}
78switch (expectedType) {
79case INT: return value instanceof Integer;
80case STRING: return value instanceof String;
81case BOOLEAN: return value instanceof Boolean;
82case ENUM: return value instanceof String; // Simplified enum check
83default: return false;
84}
85}
86
87// Helper classes for schema definition
88private enum ArgumentType { INT, STRING, BOOLEAN, ENUM }
89
90private static class ArgumentDefinition {
91private final ArgumentType type;
92private final boolean required;
93private final Object defaultValue;
94
95public ArgumentDefinition(ArgumentType type, boolean required, Object defaultValue) {
96this.type = type;
97this.required = required;
98this.defaultValue = defaultValue;
99}
100
101public ArgumentType getType() { return type; }
102public boolean isRequired() { return required; }
103public Object getDefaultValue() { return defaultValue; }
104}
105
106public static void main(String[] args) {
107// Example Usage
108System.out.println("--- getUserById ---");
109System.out.println("Valid: " + validateArguments("getUserById", Map.of("id", 123)));
110System.out.println("Missing required 'id': " + validateArguments("getUserById", Map.of()));
111System.out.println("Wrong type for 'id': " + validateArguments("getUserById", Map.of("id", "abc")));
112
113System.out.println("\n--- getProducts ---");
114System.out.println("Default args: " + validateArguments("getProducts", Map.of()));
115System.out.println("Custom args: " + validateArguments("getProducts", Map.of("category", "electronics", "limit", 50, "isActive", true)));
116System.out.println("Invalid limit: " + validateArguments("getProducts", Map.of("limit", 0)));
117System.out.println("Unknown arg: " + validateArguments("getProducts", Map.of("sort", "asc")));
118
119System.out.println("\n--- createPost ---");
120System.out.println("Valid: " + validateArguments("createPost", Map.of("title", "My Post", "content", "This is the content.", "tags", "graphql,coding")));
121System.out.println("Missing content: " + validateArguments("createPost", Map.of("title", "My Post")));
122}
123}
Algorithm description viewbox

GraphQL Argument Validation

Algorithm description:

This algorithm validates arguments passed to GraphQL fields against a predefined schema. It checks for the presence of required arguments, the correctness of argument types (e.g., integer, string, boolean), and can include specific value constraints (e.g., numeric ranges). This ensures that the server receives valid inputs, preventing errors and unexpected behavior. It's a fundamental part of GraphQL request processing.

Algorithm explanation:

The `validateArguments` function checks arguments for a given `fieldName`. It first looks up the expected arguments in `ARGUMENT_SCHEMA`. It then iterates to ensure all required arguments are present. Subsequently, it validates each provided argument: checking if the argument is known, if its type matches the schema's `ArgumentType`, and optionally performing value-specific checks (like the 'limit' range). The `isValidType` helper performs basic type checking. Time complexity is O(A), where A is the number of arguments for a field, as each argument is checked once. Space complexity is O(1) for the validation logic itself, plus the space for the schema definition.

Pseudocode:

function validateArguments(fieldName, arguments):
  if fieldName is not in ARGUMENT_SCHEMA:
    return true

  fieldArgs = ARGUMENT_SCHEMA[fieldName]

  for each argName, argDef in fieldArgs:
    if argDef.isRequired() and argName is not in arguments:
      print error "Missing required argument"
      return false

  for each argName, argValue in arguments:
    if argName is not in fieldArgs:
      print error "Unknown argument"
      return false

    argDef = fieldArgs[argName]
    if not isValidType(argValue, argDef.getType()):
      print error "Invalid type"
      return false

    // Optional: Add specific value range checks here
    if argDef.getType() is INT and argName is "limit" and (argValue <= 0 or argValue > 100):
      print error "Limit out of range"
      return false

  return true

function isValidType(value, expectedType):
  if value is null: return true
  if expectedType is INT and value is Integer: return true
  if expectedType is STRING and value is String: return true
  if expectedType is BOOLEAN and value is Boolean: return true
  if expectedType is ENUM and value is String: return true // Simplified
  return false