Given the following GraphQL schema snippet that validates an input argument age to be a positive integer, what will be the result of this query?
type Query {
user(age: Int!): String
}
# Resolver logic:
# if age <= 0, return error "Invalid age"
# else return "User age is <age>"Query:
{ user(age: -5) }Think about how the resolver handles invalid input values.
The resolver checks if the age is less than or equal to zero and returns an error message. Since -5 is invalid, it returns "Error: Invalid age".
Choose the correct syntax to validate that a string input email matches a simple email pattern using a custom directive @pattern.
Look for the correct argument name and syntax for directives.
The directive uses the argument name regex with colon syntax. Option A matches this pattern correctly.
Which of the following is the best reason to implement input validation in GraphQL APIs?
Think about security and data integrity.
Input validation helps ensure only valid data is processed, preventing errors and security vulnerabilities.
Consider this resolver function for a mutation that validates a username length:
async function createUser(parent, args) {
if (args.username.length < 3) {
throw new Error("Username too short");
}
// create user logic
return { id: 1, username: args.username };
}What error will occur if args.username is null?
What happens when you try to access .length of null?
Accessing length on null causes a TypeError because null has no properties.
You have a mutation that accepts a nested input object with multiple fields requiring validation. Which approach optimizes validation performance and maintainability?
Think about reusability and separation of concerns.
Using custom scalars and directives allows declarative, reusable validation close to the schema, improving performance and maintainability.