Input Types
Arguments so far were scalars and enums. When a field needs a structured value (a filter with several options, the data for a new record) you define an input object type with the input keyword. It looks like an object type, but it travels the other way: from client to server.
Defining an input type
input AddressInput {
street: String!
city: String!
postcode: String
country: String = "NL"
}Fields of an input type may only be scalars, enums, lists or other input types. They can't be object types, interfaces or unions, and they have no resolvers or arguments: an input is pure data.
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
input AddressInput {
street: String!
city: String!
postcode: String
country: String = "NL"
}
type Address { street: String!, city: String!, postcode: String, country: String! }
type Customer { name: String!, address: Address! }
type Query { _ping: Boolean }
type Mutation {
createCustomer(name: String!, address: AddressInput!): Customer!
}
`);
const rootValue = {
createCustomer: ({ name, address }) => {
console.log('resolver got:', JSON.stringify(address));
return { name, address };
},
};
const result = await graphql({
schema,
rootValue,
source: `mutation NewCustomer($address: AddressInput!) {
createCustomer(name: "Lieke", address: $address) {
name
address { city country }
}
}`,
variableValues: { address: { street: 'Oudegracht 1', city: 'Utrecht' } },
});
console.log(JSON.stringify(result.data));resolver got: {"street":"Oudegracht 1","city":"Utrecht","country":"NL"}
{"createCustomer":{"name":"Lieke","address":{"city":"Utrecht","country":"NL"}}}
The resolver received a plain object, with the default country already filled in. postcode was not sent and has no default, so the key is absent.
Nested inputs and lists
Inputs can contain lists and other inputs, which is great for search filters:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
enum Sort { PRICE_ASC PRICE_DESC }
input PriceRange { min: Int = 0, max: Int }
input ProductFilter {
categories: [String!]
price: PriceRange
inStockOnly: Boolean = false
}
type Product { name: String!, category: String!, price: Int!, stock: Int! }
type Query { products(filter: ProductFilter, sort: Sort = PRICE_ASC): [Product!]! }
`);
const products = [
{ name: 'Trail shoes', category: 'shoes', price: 120, stock: 3 },
{ name: 'Rain jacket', category: 'jackets', price: 90, stock: 0 },
{ name: 'Road shoes', category: 'shoes', price: 150, stock: 5 },
{ name: 'Fleece', category: 'jackets', price: 60, stock: 8 },
];
const rootValue = {
products: ({ filter = {}, sort }) => {
const { categories, price = {}, inStockOnly } = filter;
const max = price.max ?? Infinity;
const min = price.min ?? 0;
return products
.filter((p) => !categories || categories.includes(p.category))
.filter((p) => p.price >= min && p.price <= max)
.filter((p) => !inStockOnly || p.stock > 0)
.sort((a, b) => (sort === 'PRICE_ASC' ? a.price - b.price : b.price - a.price));
},
};
const query = `query Shop($filter: ProductFilter, $sort: Sort) {
products(filter: $filter, sort: $sort) { name price }
}`;
const runWith = async (variableValues) => {
const result = await graphql({ schema, source: query, rootValue, variableValues });
console.log(JSON.stringify(result.data.products.map((p) => `${p.name} ${p.price}`)));
};
await runWith({});
await runWith({ filter: { price: { max: 120 }, inStockOnly: true } });
await runWith({ filter: { categories: ['shoes'] }, sort: 'PRICE_DESC' });["Fleece 60","Rain jacket 90","Trail shoes 120","Road shoes 150"]
["Fleece 60","Trail shoes 120"]
["Road shoes 150","Trail shoes 120"]
Validation of input objects
Unknown fields, missing required fields and wrong types are all rejected before the resolver runs:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
input TagInput { name: String!, color: String }
type Query { preview(tag: TagInput!): String }
`);
const rootValue = { preview: ({ tag }) => `#${tag.name}` };
const query = 'query P($tag: TagInput!) { preview(tag: $tag) }';
for (const tag of [{ name: 'news' }, { color: 'red' }, { name: 'news', size: 3 }, { name: 7 }]) {
const result = await graphql({ schema, source: query, rootValue, variableValues: { tag } });
console.log(result.errors ? result.errors[0].message : result.data.preview);
}#news
Variable "$tag" got invalid value { color: "red" }; Field "name" of required type "String!" was not provided.
Variable "$tag" got invalid value { name: "news", size: 3 }; Field "size" is not defined by type "TagInput".
Variable "$tag" got invalid value 7 at "tag.name"; String cannot represent a non string value: 7
Why not reuse output types as inputs?
It's tempting to write createUser(user: User), but GraphQL forbids object types as arguments, for good reasons:
- Output types have fields that clients must not set (
id,createdAt, computed fields with arguments). - Output fields can be interfaces, unions or cycles, which have no sensible input meaning.
- Create and update usually differ: on create
titleis required, on update everything is optional.
So it's normal to have Post, CreatePostInput and UpdatePostInput side by side.
@oneOf input objects
A newer addition (supported in graphql-js 16.9+) is @oneOf: exactly one field must be set. It models "find a user by id or by email":
input UserBy @oneOf {
id: ID
email: String
}
type Query { user(by: UserBy!): User }Test yourself
Which keyword defines a type that can be used as an argument value?
typeinputscalarargument
Which of these is NOT allowed as a field type inside an input object?
String!- An enum
- Another input type
- An object type like
User
Why do APIs often have both CreatePostInput and UpdatePostInput?
- GraphQL requires two inputs per type
- Create and update usually need different required fields
- Input types can only be used once
- For performance