3. The input type
5m

Overview

In Odyssey Lift-off III, we learned that we can define for a in our schema, which the field's can use. In that course, we only defined a single argument for a field, so our schema stayed pretty simple and clean.

But in Airlock, some of our require several all at once. How can we keep our schema easy to read while also providing our the data they need? The answer: with input types!

In this lesson, we will:

  • Learn about the input type
  • Discover the benefits of using an input type for s
  • See an example of how the input type is used in the Airlock codebase

What is the input type?

The input type in a is a special that groups a set of together, and can then be used as an argument to another .

Using input types helps us group and understand , especially for . For example, when creating a listing in Airlock, we know the needs to include a bunch of data about the listing (title, description, photo thumbnail, number of beds, cost per night, location type, and amenities). We could list out all those inside the createListing , but that can get unwieldy and hard to understand.

Instead, we can create an input type called CreateListingInput and list all the necessary there. That way, we can keep the definition clear, and we can also reuse that input type in other mutations that require the same set of .

Defining an input

To define an input type, use the input keyword followed by the name and curly braces ({}). Inside the curly braces, we list the and types as usual. Note that fields of an input type can be only a , an enum, or another input type.

Here's an example of another input type from the Airlock schema:

server/schema.graphql
input SearchListingsInput {
checkInDate: String!
checkOutDate: String!
numOfBeds: Int
page: Int
limit: Int
sortBy: SortByCriteria # this is an enum type
}

Using the input

To use an input type in the schema, we can set it as the type of a . For example, the searchListings uses the SearchListingsInput type like so:

server/schema.graphql
type Query {
# ...
"Search results for listings that fit the criteria provided"
searchListings(criteria: SearchListingsInput): [Listing]!
# ...
}

Note: Input types can be reused in multiple , but be careful when using the same input type for both queries and ! Some that may be required in mutations may not be required for queries.


For more details, check out the Apollo docs on input types.

See it in the Airlock codebase

There are multiple inputs defined in the Airlock schema. Check them out in the server/schema.graphql file.

  • What do you notice about the existing inputs?
  • How are the inputs used in the client code?

Practice

How can we use the input type in our schema?

Key takeaways

  • The input type is a special used as to . This allows us to group and understand all of our arguments together, especially for .

Up next

In the next lesson, we'll learn another tool for grouping related attributes: interfaces.

Previous