logo

NJP

GraphQL Fragments - Learn Integrations on the Now Platform

Import · Dec 04, 2023 · video

[Music] in this video we'll look at ways to make our queries easy to maintain when we start seeing the same sequence of fields appear in our queries let's review that earlier example of the query for the complex data type user notice that the Field's ID name and email appear here and here let's take a programmatic approach to create a macro as it were to use instead of the repeated code this is the purpose of a graphql fragment a fragment is a reusable unit in graphql that allows us to construct sets of fields that we can include in multiple operations we'll Define the fragment in our code below the query block by starting with the keyword fragment then giving it a name we'll call ours user fields we then describe where we wish it to apply with the on keyword and the data type in the schema for this we'll call upon the graphql Explorer introspection to help when we start typing X we get possible options in that list we can quickly narrow down the ones that start with x snc mm from our scope then case queries from our API name and finally we select the one that ends with user next we'll copy the fields from here and paste them into the fragment now we can replace the series of fields in the query with the shortcut dot dot dot user Fields here and here and when we run the query we see that it produces the exact same results okay that wasn't terribly exciting but let's say later someone asked us to add the active field to our query fragments make it easy to add once and apply it wherever the fragment is used let's do that here and run the query again boom fragments make it easy to write and maintain graphql queries when we have repeated sections of fields I hope you join me for the next video

View original source

https://www.youtube.com/watch?v=i6cJj5RJyjU