Named Operations3:21 with Isaac Lee Morris
We will learn how queries and mutations can both be named and reused.
(Apollo's Launchpad has been deprecated, so your screen will look different)
- Alias - A syntax for renaming the result of a field to anything you want
[MUSIC] 0:00 Welcome to the final stage of Introduction to GraphicQL. 0:04 So far, we've practiced retrieving and 0:09 modifying data using the GraphicQL query language. 0:11 In this final stage, I'll show you a couple tricks 0:15 that will make your GraphicQL queries cleaner and more reusable. 0:18 The first concept we'll go over is aliases, 0:23 aliases are used to rename the content of a query. 0:27 This is great when we want to include the results from multiple queries to the same 0:30 endpoint in a single response. 0:35 Let's head over to Launchpad to see how it works. 0:37 To better illustrate the need for aliases, let's try querying for 0:41 two movies using what we know so far. 0:45 The end point we'll use is the movie by ID end point. 0:48 Let's start by taking a look at the movie ID schema, 0:52 in the back end editor pane, under typeDefs. 0:56 Looks like this endpoint just takes a movie ID argument of type ID. 1:00 Following that, after the colon, 1:06 we can see that this endpoint returns a movie object. 1:08 Now that we know what we're working with, we can go ahead and 1:12 start writing our query, so we'll start with the declaration. 1:16 And we're querying movieById. 1:24 And the movieId that we'll pass in, we'll just use movie_0. 1:28 As always, we need to pick some fields to return, in this case, 1:35 we'll just go with id and title, go ahead and click Play, 1:39 As we can see, this works fine, but what happens when we add a second movie? 1:46 Well, let's try it out, so underneath the first query, 1:52 we''ll add another movieById. 1:57 This time, the movieId we'll use is movie_1, 2:04 Again, we'll specify that we want the id and title fields returned, and click Play. 2:10 Hm, looks like GraphQL didn't like that, but why not? 2:18 The reason this won't work is that there's a name collision between the two calls. 2:23 In other words, they both ask for the same endpoint, and 2:28 only one value can be returned for each endpoint. 2:32 So how do we solve this, well, it's actually pretty simple. 2:36 We just need to specify an alias for each response to be nested under, so 2:41 they no longer collide. 2:45 So for the first movie, we'll add an alias called movieOne. 2:47 You can go ahead and add that alias right in front of the end point name. 2:51 Then for the second movie, we'll give that an alias of movieTwo. 2:58 Again, add a colon right in front of the endpoint name, 3:03 now go ahead and click Play. 3:07 As you can see, this time we were able to get the response, and 3:11 it was nested under the aliases that we created. 3:14
You need to sign up for Treehouse in order to download course files.Sign up