❓ Querying for a specific track
We've updated our schema with new fields and the
Module type, but we still need a way to query for a specific track by its ID. To do that, we'll need to add another entry point to our schema.
schema.js file in the
server/src folder, we can see that we only have a single entry point to our API so far: the
tracksForHome field that returns a list of
Tracks. Let's add another one called
track, which will return a single
Query type in
Where can we add entry points to our schema?
We'll be able to specify which unique track we're querying for by giving this field an argument.
🤔 How to use GraphQL arguments
An argument is a value you provide for a particular field in your query. The schema defines the arguments that each of your fields accepts.
Your resolvers can then use a field's provided arguments to help determine how to populate the data for that field. Arguments can help you retrieve specific objects, filter through a set of objects, or even transform the field's returned value. A query that performs a search usually provides the user's search term as an argument.
To define an argument for a field in our schema, we add parentheses after the field name. Inside, we write the name of the argument followed by a colon, then the type of that argument, like
Int. If we have more than one argument, we can separate them with commas.
Which of these are reasons to use arguments in a query?
🙌 Using arguments
In our case, we want to use the track's ID as our argument. Following the syntax rules, we'll add the parentheses, then the name
id, with the type
ID which is required.
Query type in
schema.js, update the
track field to:
"Fetch a specific track, provided a track's ID"track(id: ID!): Track
spacecat. This field takes an argument
idof type non-nullable
IDand returns a nullable
SpaceCat. 2) Query for a list of
missions. This field takes 2 arguments:
toof nullable type
String(to specify the mission destination), and
scheduledof nullable type
Boolean(to filter for scheduled or unscheduled missions). This field returns a nullable array of nullable
That's it for the query definition. We now have our schema up-to-date for the feature we're implementing. Onwards to the resolver!