ScandiPWA
Create Magento AppCreate ScandiPWA AppUser ManualGitHub
  • Why Scandi
  • πŸš€Quick-start Guide
  • πŸ—ΊοΈRoadmap
  • Introduction to the Stack
    • CMA, CSA, and ScandiPWA
    • Challenges
  • Setting up Scandi
    • Storefront Mode Setup
      • Proxying requests to server
    • Magento Mode Setup
    • Existing Magento 2 setup
    • Magento Commerce Cloud setup
    • Updating to new releases
      • Storefront mode upgrade
      • Magento mode upgrade
      • CMA upgrade
      • CSA upgrade
      • Custom ScandiPWA composer dependency update
      • Local ScandiPWA Composer Package Setup
    • Docker Setup [deprecated]
      • Legacy Docker setup
      • Migrating to CMA & CSA
  • Developing with Scandi
    • Override Mechanism
      • Overriding JavaScript
        • Overriding classes
        • Overriding non-classes
      • Overriding Styles
      • Overriding the HTML / PHP
      • Parent Themes
    • Extensions
      • Creating an extension
      • Installing an extension
      • Migrating from 3.x to 4.x
      • Publishing an extension
      • Extension Terminology
    • Working With Magento
      • Magento troubleshooting
      • Working with Magento modules
      • Working with GraphQL
      • GraphQL Security
      • Working with "granular cache"
    • Developer Tools
      • Debugging in VSCode
      • ScandiPWA CLI
      • Configuring ESLint
      • CSA Commands
    • Deploying Your App
      • Build & Deploy Android app
      • Build & Deploy iOS app
  • Structure
    • Directory Structure
    • Building Blocks
      • Components
        • Styling Components
      • Routes
      • Redux Stores
      • GraphQL Queries
      • Global Styles
      • The Util Directory
      • Type Checking
    • Application assets
    • Code Style
      • JavaScript Code Style
      • SCSS Code Style
  • Tutorials
    • Customizing Your Theme
      • Styling
        • Customizing the Global Styles
        • Adding a New Font
        • Overriding a Components Styles
        • Extending a Component's Styles
      • Customizing JavaScript
        • Customizing the Footer Copyright
        • Adding a New Page
        • Adding a Section in My Account
        • Adding a Tab on the Product Page
        • Creating a New Redux Store
    • Payment Method Integration
      • Setting Up for Development
      • Redirecting to the Payment Provider
      • Handling the Customer's Return
    • Creating a Custom Widget
      • Scandi CMS System Overview
      • Creating a Magento Widget
      • Implementing the Rendering
    • Video Tutorials
      • #1 Setting up and talking theory
      • #2 Templating in React
      • #3 Overriding a file
      • #4 Styling the application
      • #5 Patterns of ScandiPWA
    • Dark Mode Extension
    • Deploying Native Apps
    • Product 3D Model Extension
      • Part 1: Magento 3D Model Uploads
      • Part 2: GraphQL API
      • Part 3: Scandi Frontend
    • Social Share, Full Extension Development
      • STEP-1 and 2 Creating Magento 2 Module
      • STEP-3 Backend Configurations Settings
      • STEP-4 Simple GraphQl and Resolver
      • STEP-5 Creating Extension, Base Redux Store
      • STEP-6 Extension plugins
      • STEP-7 GraphQL types, Helpers
      • STEP-8 Query Field and FieldList
      • STEP-9 render Plugins and MSTP Plugin, Component creation
      • STEP-10 SocialShare Component Development
      • STEP-11 SocialShare for CategoryPage
      • TASK-1 Changing LinkedIn to Twitter
      • STEP-12 Comments for Admin Users
      • STEP-13 Final, bugfixes
    • Accessing Magento 2 Controllers
      • STEP-1 Creating Magento 2 Module
      • STEP-2 - Create Magento 2 Frontend Route and Basic Controller
      • STEP-3 Accessing Magento 2 Controller, Bypassing ScandiPWA frontend
      • STEP-4 Creating ScandiPWA Extension with additional dependencies
      • STEP-5 Creating Plugin and Axios request
  • About
    • Support
    • Release notes
    • Technical Information
    • Data Analytics
    • Contributing
      • Installation from Fork
      • Repository structure
      • Code contribution process
      • Submitting an Issue
      • Publishing ScandiPWA
Powered by GitBook
On this page
  • Defining a Query
  • Implementing a Resolver
  • Testing the Query
  • Extending Existing Resolvers

Was this helpful?

  1. Developing with Scandi
  2. Working With Magento

Working with GraphQL

PreviousWorking with Magento modulesNextGraphQL Security

Last updated 4 years ago

Was this helpful?

ScandiPWA requests the data it needs from Magento via GraphQL. By default, Magento already defines a GraphQL schema and corresponding resolvers, enabling the frontend to request certain data via GraphQL. However, the API provided by Magento is not complete, so ScandiPWA has a set of custom modules that extend it to serve a broader range of data.

If you need develop custom backend functionality in your site, or if you want to adapt existing functionality to ScandiPWA, you will need to make sure it can be accessible via GraphQL.

Technically, you could fetch data using a REST API as well, but this has several disadvantages and is discouraged . The ScandiPWA codebase entirely uses GraphQL.

Defining a Query

A GraphQL schema describes what types of data the GraphQL server deals with, what queries and mutations it provides, as well as the expected parameters and responses of those queries.

Queries and Mutations in GraphQL are like GET and POST request endpoints in REST – they implement one specific functionality of the API. A key difference is that all queries and mutations are done through one actual endpoint, managed by GraphQL. This allows for more flexibility. You can read an if you are not familiar with it.

In Magento, you can extend the schema by creating a GraphQL schema file, at etc/schema.graphqls in your module. The schema files from all modules get merged together to producs the final schema, accessible to the frontend. This means that you can define new queries or types, as well as extend existing types.

Consider this example :

scandipwa/catalog-graphql/src/etc/schema.graphqls (annotated excerpt)
# this block contains the queries we define in this schema file
type Query {
    category (
        id: Int @doc(description: "Ids of the category")
        url_path: String @doc(description: "Url path of the category")
    ): CategoryTree
    @resolver(class: "ScandiPWA\\CatalogGraphQl\\Model\\Resolver\\CategoryTree")
}

# this type is already defined elsewhere; we merely want to add
# another field to it
type CategoryTree {
    is_active: Boolean @doc(description: "Category is enabled")
}

In GraphQL, types followed by an exclamation mark ! are required. Since we have specified id: Int and not id: Int!, neither of the parameters are required.

This schema defines a new GraphQL query that accepts either an id or url_path and returns a category. The CategoryTree type is already defined elsewhere fields representing a category, so we don't need to re-define that. We do, however, want to add a new field to specify if the category is enabled.

Implementing a Resolver

A GraphQL resolver is a piece of PHP code that actually implements the queries defined in the Schema. It takes the query parameters as function arguments, and must return a PHP array or associative array of the shape specified in the schema.

The query defined in the schema above specifies a resolver class using the @resolver annotation. The Magento GraphQL mechanism will use this class whenever a cmsPage query is made.

By convention, resolvers are located in the Model/Resolver directory of the module. All resolvers must implement the Magento\Framework\GraphQl\Query\ResolverInterface to ensure they are able to work with the GraphQL system.

Here is the resolver used by the category query:

scandipwa/catalog-graphql/src/Model/Resolver/CategoryTree.php (simplified)
class CategoryTree implements ResolverInterface
{
    // [...] field declarations, constructor using dependency injection

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context, // some context info (e.g. the user ID if any)
        ResolveInfo $info,
        array $value = null,
        array $args = null // an associative array of the parameters passed
    ) {
        $rootCategoryId = $this->getCategoryId($args);

        // a bunch of helper functions.
        // $category ends up being an array-like value with the data we want
        $categoriesTree = $this->categoryTree->getTree($info, $rootCategoryId);
        $result = $this->extractDataFromCategoryTree->execute($categoriesTree);
        $category = current($result);

        return $category;
    }
}

When writing most simple resolvers, you will need to know:

  • $context contains some information about the user's session

  • $args contain the arguments passed to the query/mutation

  • The function must return an array containing the data you want the query to return

Testing the Query

Extending Existing Resolvers

You can use a tool such as or another GraphQL client to check that your query is working properly. The GraphQL endpoint, by default, is <your-server>/graphql.

If your query works as expected, you can now !

Resolvers, like any other Magento class, can be extended using , or the DI preference mechanism. You can also extend the GraphQL types of their responses to specify that they now return some new field as well.

Altair GraphQL
use it on the frontend
Magento Plugins (interceptors)
introduction to GraphQL
schema
in favor of GraphQL