Enabling GraphQL in stores

This tutorial will show you how to set up GraphQL in your store.

Procedure

  1. Add a proxy for GraphQL in setupProxy.js.
    1. Create a host for GraphQL in setupproxy.js.
      const GRAPHQL_HOST = http://localhost:3100
      Note: If you are using HTTPS use port 3443.
      = https://localhost:3443
    2. Define the GraphQL context in setupProxy.js.
      const GraphQLContext = {
        target: GRAPHQL_HOST,
        ...options
                   }
    3. Define the middleware for GraphQL in setupProxy.js.
      app.use ("/GraphQL”, createProxyMiddleware(graphQLContext))
  2. Add constant in store-web\src\_foundation\common.ts.

    export const GRAPHQL = "graphQL".

  3. Add information in SiteInfoService.ts.
    Set local storage variable in SiteInfoService.ts.
    const is GraphQL = storeviewURL.searchParams.get (GRAPHQL);
    if (isGraphQL) {
          localStorageUtil.set (GRAPHQL, isGraphQL, 30);
       }
    
  4. Create a GraphQL service file in Emerald store and add it to the api/transaction folder.
    Note:
    • Refer to the GraphQL.Service_Sample file for a sample format of the GraplQl.Service file.
    • This provided GraphQL_Service file is only for reference and you must create your own GraphQL service file.
  5. Import GraphQL service in desired component.

    For example, if you want to use GraphQL in order component, then you need to import GraphQL service in order component.

    Import GraphQLService from ../../../_foundation/apis/transaction/graphQL.service.

  6. Add flag in the desired component where we want to use GraphQL query.
    1. If you want to use GraphQL query in order page for fetch cart API, you need to add condition-based logic in resource call.
      const responseCart = yield call (
              localStorageUtil.get (GRAPHQL)
                ? graphQLService.getCart
                : cartService.getCart,
              {...parameters}
      );
    2. Since the response structure in GraphQL is bit different, you will need to extract the data and assign it to the desired variable.

      The REST response for the above resource call data would be returned as responseCart = {data: {}}

      In GraphQL it would be returned as responseCart = {data: {data: {cartGetCart: {}}}}

  7. Execute GraphQL query from Store.

    By default, GraphQL is disabled in Store; if you want to enable GraphQL queries in Store, you must provide graphQL=true in the browser URL.

    The following is an example of a sample store called Emerald.

    If you are using Emerald store and want to enable GraphQL in Emerald, you can add graphQL=true

    http://localhost:3000/Emerald?graphQL=true