Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The persisted query is a definition of the query for the frontend front-end component to import. We name this file the query name, minus the component name of the plugin we’re working with.

...

  • Create the persisted query file in the webapi/ajax/items.graphql with the following:

    Code Block
    language
    graphql
    query local_todo_items {
        local_todo_items {
            items {
                id
                title
                completed_at
            }
        }
    }

Create the backend

Now we need to create the PHP backend to handle the query.

  • First we’ll create the directory for the query resolver by creating the following directory: /server/local/todo/classes/webapi/resolver/query

  • Now let’s create the query resolver class, items.php in the directory we just created.:

    Code Block

    • Code Block
      languagephp
      <?php
      
      namespace local_todo\webapi\resolver\query;
      
      use core\webapi\execution_context;
      use core\webapi\query_resolver;
      use local_todo\entity\item;
      
      class items extends query_resolver {
      
          /**
           * @inheritDoc
           * @throws \coding_exception
           */
          public static function resolve(array $args, execution_context $ec) {
              global $USER;
      
              $items = item::repository()
                  ->where('user_id', $USER->id)
                  ->order_by('id')
                  ->get();
      
              return ['items' => $items];
          }
      }
    • In this file we’ve defined the query resolve and we’re using the ORM of local_todo to return a list of items.

  • Now we create the type resolver directory /server/local/todo/classes/webapi/resolver/type/ and the type resolver for item item.php in the directory.:

    Code Block
    languagephp
    <?php
    
    namespace local_todo\webapi\resolver\type;
    
    use core\webapi\execution_context;
    use core\webapi\type_resolver;
    
    class item extends type_resolver {
        /**
         * @param string $field - The field being requested 
         * @param $source - In the case, source will be our `item` entity class as it's what's returned from the query resolver
         * @param array $args
         * @param execution_context $ec
         * @return mixed|void
         */
        public static function resolve(string $field, $source, array $args, execution_context $ec) {
            return $source->$field;
        }
    }

Testing queries and mutations

...