GraphQL within OXID eShop

GraphQL?

  • a query language for your API
  • ask for what you need, get exactly that
  • get many resources in a single request
  • describe what’s possible with a type system

Start with a schema definition

type Query {
    category(id: String!): Category
}

type Category {
    id: ID!
    title: String!
    active: Bool!
    articles: [Article]
    parent: Category
    siblings: [Category]
    children: [Category]
}

type Article {
    id: ID!
    title: String!
    category: Category
}

How to query that

{
    query {
        category(id: "943a9ba3050e78b443c16e043ae60ef3") {
            id
            title
            children {
                id
                title
            }
        }
    }
}

What do you get?

{
  "data": {
    "category": {
      "id": "943a9ba3050e78b443c16e043ae60ef3",
      "title": "Kiteboarding",
      "children": [
        {
          "id": "0f41a4463b227c437f6e6bf57b1697c4",
          "title": "Trapeze"
        },
        {
          "id": "0f4f08358666c54b4fde3d83d2b7ef04",
          "title": "Kiteboards"
        }
      ]
    }
  }
}

GraphQLite

Create a complete GraphQL API by simply annotating your PHP classes
— GraphQLite docs

Basic Example - Controller

class CategoryController
{
    /**
     * @Query()
     */
    public function category(string $id): Category
    {
        // Some code that looks for a category and returns it.
    }
}

Basic Example - Type

/**
 * @Type()
 */
class Category
{
    /**
     * @Field()
     */
    public function getTitle(): string
    {
        return $this->title;
    }
    // ...
}

Basic Example - The Schema

type Query {
    category(id: String!): Category
}

type Category {
    title: String!
}

Howto get this running in OXID?

oxid-esales/graphql-base

  • bootstrap GraphQLite
  • auth using JWT

Howto use this in my module?

  • create a namespace mapper class
  • tag this class graphql_namespace_mapper in services.yaml
  • create a permission provider class
  • tag this class graphql_permission_provider in services.yaml

Sounds complicated?

composer create-project oxid-esales/graphql-module-skeleton

Demo time

Further readings

  • https://graphql.org
  • https://graphqlite.thecodingmachine.io/
  • https://github.com/OXID-eSales/graphql-base-module
  • https://github.com/OXID-eSales/graphql-storefront-module