What you'll learn
  • how to extend the Headless CMS-related GraphQL types and operations

Use the webiny watch command to continuously deploy application code changes into the cloud and instantly see them in action. For quick (manual) testing, you can use the built-in API Playground.

Custom Queries
anchor

Let’s say we wanted to extend our GraphQL schema with a custom listMyPosts query, which, as the name suggests, would enable us to quickly retrieve all posts created via the Headless CMS application, for the currently logged in user.

In other words, we want to return all content entries of the Post content model, where the createdBy points to the currently logged in user. For demonstration purposes, our Post content model will be very simple:

The Post Content ModelThe Post Content Model
(click to enlarge)

The createdBy field is automatically assigned to every content entry and it represents the currently logged in user.

Creating the new listMyPosts query can be achieved via a single CmsGraphQLSchemaPluginexternal link plugin.

apps/api/graphql/src/plugins/posts.ts

The code above can be placed in the apps/api/graphql/src/plugins/posts.tsexternal link file, which doesn’t exist by default, so you will have to create it manually. Furthermore, once the file is created, make sure that it’s actually imported and registered in the apps/api/graphql/src/index.tsexternal link entrypoint file.

With all the changes in place, we should be able to run the following GraphQL mutation:

For example:

Using the listMyPosts QueryUsing the listMyPosts Query
(click to enlarge)

As we can see, the listPosts query returned a total of three posts. On the other hand, the listMyPosts only returned posts for the currently logged-in user, which is the expected result.

FAQ
anchor

What Is thecontextObject, and Where Are All of Its Properties Coming From?
anchor

In the shown examples, you may have noticed the use of the context object in GraphQL resolver functions. This object contains multiple different properties, mainly being defined from different Webiny applications that were imported in the GraphQL API’s apps/api/graphql/src/index.tsexternal link entrypoint file.

That’s why, for example, we were able to utilize the cms.models.getexternal link and cms.entries.listLatestexternal link methods.

For easier discovery and type safety, we suggest a type is always assigned to the context object in your GraphQL resolver functions.