Skip to content

Instantly share code, notes, and snippets.

@benjie
Last active April 4, 2025 13:07
Show Gist options
  • Save benjie/58ba75340a85b0da4b403973bea2c5fb to your computer and use it in GitHub Desktop.
Save benjie/58ba75340a85b0da4b403973bea2c5fb to your computer and use it in GitHub Desktop.
GraphQL.js accepts arrays as input object inputs

If you pass an array in place of an input object, an error is raised for each individual field that doesn't match, plus each "extra key" the array has (i.e. numeric indicies).

mkdir demo
cd demo
yarn add graphql @graphql-tools/schema
node repro.mjs

Expected result: one error (user is not an object)

Actual result: 6 errors (one for each missing key, and one for each array index)

// @ts-check
import { makeExecutableSchema } from "@graphql-tools/schema";
import { graphql, validateSchema } from "graphql";
const schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
input UserInput {
firstName: String!
lastName: String!
businessPhone: String!
email: String!
jobTitle: String
}
type User {
firstName: String!
lastName: String!
businessPhone: String!
email: String!
jobTitle: String
}
type Mutation {
updateUser(user: UserInput!): User!
}
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => "Hello, world!",
},
Mutation: {
updateUser: (_, { user }) => {
console.log("Received user input:", user);
return {
firstName: user.firstName,
lastName: user.lastName,
businessPhone: user.businessPhone,
email: user.email,
jobTitle: user.jobTitle || null,
};
},
},
},
});
const errors = validateSchema(schema);
if (errors.length > 0) {
console.dir(errors);
throw new Error("Invalid schema");
}
const result = await graphql({
schema,
source: /* GraphQL */ `
mutation UpdateUser($user: UserInput!) {
updateUser(user: $user) {
firstName
lastName
}
}
`,
variableValues: {
user: [{ firstName: "Alice" }, { firstName: "Bob" }],
},
});
console.dir(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment