Skip to main content

Define your own Custom GraphQL schema in Sitecore GraphQL

As more and more usage of Sitecore JSS with Javascript frameworks like React JS, Vue.JS and Angular JS, it is very important know that GraphQL is becoming mandatory for Enterprise Applications. In an Enterprise Application, querying different API with different kinds of integration of back-end system is very important. Sitecore GraphQL plays a very important role in this regard.

If you are new to Sitecore GraphQL and wanted to know how to set it up , Click Here for the link where I have documented step by step approach to set up on Sitecore. Let's proceed further.

What is Graphql Schema?
Schemas describe the way that data is organized and constructed. A GraphQL schema defines the types and the fields available on each type, which can include references to other types. You can use a schema provider to add self-contained pieces of a schema.  If you want to add a new root query and your type system does not depend on any other schema provider’s types, you must select a schema provider. Few of the good examples of schema provider are a third party CRM System, a Product Catalog etc.,

With that being said, we cannot rely only the OOTB box Sitecore data. There is need to define your own set of schema to define to target your need.

Building the Sitecore GraphQL SchemaProvider

This post walks you through the following steps to guide you setting up a custom GraphQL SchemaProvider from which you can query the endpoint.

Steps to create your own GraphQL schema in Sitecore:

Create .NET project with SchemaProvider, GraphType(s) and RootQuery
Register the newly created Schema Provider as a GraphQL endpoint

Step 1: Implement a schema provider
First step to define your own custom schema is to implement a schema provider:
Create a C# class that implements the SchemaProviderBase class. This class defines the structure of the GraphQL schema, including the root fields that can be queried (an item is a root query field in the content schema provider).
Here I am creating a custom GraphQL schema called company. Name of the SchemaProvider class is ProductionCompanySchemaProvider. Also, this includes other necessary .Net code as a separate classes. Entire code is uploaded here

//1. ProductionCompanySchemaProvider.cs defines the custom schema and calls CompanyQuery for data

using GraphQL.Types;
using Sitecore.Services.GraphQL.Schemas;
using System.Collections.Generic;

namespace Sitecore.GraphQL.CustomSchema
{
	public class ProductionCompanySchemaProvider : SchemaProviderBase
	{
		public override IEnumerable CreateRootQueries()
		{
			yield return new CompanyQuery();
		}
	}
}

//2. CompanyQuery.cs defines the RootFieldType, Resolve FieldContext and retuns the company data

using GraphQL.Types;
using Sitecore.Services.GraphQL.Schemas;

namespace Sitecore.GraphQL.CustomSchema
{

	/// Teaches GraphQL how to resolve the `Company` root field.
	/// RootFieldType means this root field maps a `ProductionCompany` domain object into the `ProductionCompanyGraphType` graph type object.
	public class CompanyQuery : RootFieldType
	{
		public CompanyQuery() : base(name: "company", description: "Gets the production company details")
		{
		}

		protected override ProductionCompany Resolve(ResolveFieldContext context)
		{
			// this is the object the resolver maps onto the graph type
			// (see ProductionCompanyGraphType below). This is your own domain object, not GraphQL-specific.
			return new ProductionCompany
			{
				Id = 123,
				Name = "Mindtree Ltd an L&T Company",
				LogoPath = "c://abc/xyz/logo.png",
				OriginCountry = "Mindtree Ltd"
			};
		}
	}
}

//3. ProductionCompanyGraphType.cs returns the FieldType

using GraphQL.Types;

namespace Sitecore.GraphQL.CustomSchema
{
	// because this graph type is referred to by the return type in the FieldType, it is automatically
	// registered with the schema. For implied types (e.g. interface implementations) you need to override CreateGraphTypes() and
	// manually tell the schema they exist (because no graph type directly refers to those types)

	public class ProductionCompanyGraphType : ObjectGraphType
	{
		public ProductionCompanyGraphType()
		{
			// graph type names must be unique within a schema, so if defining a multiple-schema-provider
			// endpoint, ensure that you don't have name collisions between schema providers.
			Name = "ProductionCompany";
			Field>("id", resolve: context => context.Source.Id);
			Field>("name", resolve: context => context.Source.Name);
			Field>("logo_path", resolve: context => context.Source.LogoPath);
			Field>("origin_country", resolve: context => context.Source.OriginCountry);
		}
	}
}

//4. PorductionCompany.cs model class

namespace Sitecore.GraphQL.CustomSchema
{
	public class ProductionCompany
	{
		public int Id { get; set; }
		public string Name { get; set; }
		public string LogoPath { get; set; }
		public string OriginCountry { get; set; }
	}
}


Step 2: Create Sitecore config patch to define the GraphQL endpoint.
Register the schema provider as a GraphQL endpoint using Sitecore config patch.

<sitecore>
 <api>
   <GraphQL>
       <endpoints>
          <master type="Sitecore.Services.GraphQL.Hosting.GraphQLEndpoint, 
           Sitecore.Services.GraphQL.NetFxHost">
              <schema hint="list:AddSchemaProvider">
                <company type="Sitecore.GraphQL.CustomSchema.ProductionCompanySchemaProvider, 
                  Sitecore.GraphQL.CustomSchema" />
              </schema>
           </master>
       </endpoints>
    </GraphQL>
  </api>
</sitecore>

Post this follow these steps:
Build the your GraphQL SchemaProvider project and place the dll in the bin folder of your Sitecore instance webroot and
Copy the Sitecore patch config into AppConfig/Include folder. For example in my case C:\inetpub\wwwroot\site93sc.dev.local\App_Config\Include\zzcustompatches
Run the Sitecore Graph Browser url with ApiKey. For example https://site93sc.dev.local/sitecore/api/graph/items/master/ui?sc_apikey=%7B03676D92-E472-4AFA-BF72-DE4B38C0128A%8D
Now, your environment will be ready to execute queries on your custom GraphQL schema i.e company Here is one such screenshot which i captured after executing query
You can create custom GraphQL schema to even call your different service data and query the same using GraphQL.
You can find the code and config uploaded here in GitHub.

Comments

Popular posts from this blog

Steps to create a Sitecore JSS app and Deploy to Sitecore

If you are a beginner in Sitecore JSS and you are looking step-by-step by process to setup your first JSS App with Sitecore, please proceed further and setup up your first JSS App along with deploying it to Sitecore. Before we jump start creating JSS APP, let us start with a quick introduction to Sitecore JSS. What is Sitecore JSS?  Sitecore JavaScript Services (JSS) is a complete SDK for JavaScript developers that enables you to build full-fledged solutions using Sitecore and modern JavaScript UI libraries and frameworks. Build Headless JavaScript applications with the power of Sitecore. Use your favorite JavaScript framework powered by an enterprise experience platform like React, Angular or Vue.js. Prerequisites for Connected mode with Sitecore Required Installations node.js v6.9 or later npm v5.7 or later Sitecore 9 or later installation with JSS(For JSS component ref, https://dev.sitecore.net/Downloads/Sitecore_JavaScript_Services.aspx) Required Settings  Sitecore

Custom Fields in Sitecore (Custom DropLink, DropTree, MultiList, TreeList and Required Field Validator)

Custom Fields in Sitecore Just thought to share few of the custom Sitecore fields that I have created for one of the sample project. This may help the community memebers to easily incorporate them into their project if they need any of them. Here are few. 1. Custom DropLink using Sitecore.Data.Items; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; namespace SitecoreCustom.Web.Extensions.CustomFields { public class CustomDropLink : Sitecore.Shell.Applications.ContentEditor.LookupEx { protected override void DoRender(System.Web.UI.HtmlTextWriter output) { this.ExcludeItems(); base.DoRender(output); } private void ExcludeItems() { Item item = Sitecore.Context.ContentDatabase.GetItem(base.ItemID); var LinkedField= Sitecore.StringUtil.ExtractParamete

Sitecore JSS - Custom Rendering Content Resolvers

In Sitecore, while working for real-time projects, you may get scenarios where you would see a need to customize you rendering output to serialze. Sitecore provides three different ways of customizing your rendering output with Sitecore JSS. They are as below. • Use JSS GraphQL Support - Using Integrated GraphQL queries • Use Out-of-the-box Rendering Content Resolvers - Using Sitecore JSS built-in Rendering Content Resolvers • Implementing a Custom Rendering Content Resolvers by inheriting RenderingContentsResolver Why Customization? In Sitecore development, many times we encounter scenarios to deal with hierarchical item structures like multi-level menu, product category, product sub-category, product details, forms etc., and even, in case where there is a need to combine the Sitecore data with any non-Sitecore data. In these types, Sitecore JSS is not able to serialize item structures with sub-hierarchies into JSON. Sitecore Jss allow us custiomize in