Les schémas GraphQL

Les schémas GraphQL

22 October 2021

Toutes nos données seront stockées en base de données via MySQL, mais notre API utilisera GraphQL pour les retourner. Pour cela, nous allons créer deux entités avant de configurer nos schémas.

Il s'agira de gérer des artistes et leurs albums.

Lancez la commande :

symfony console make:entity Artist
# php bin/console make:entity Artist

Voilà l'entité à créer. Si vous ne savez pas encore générer des entités, je vous conseille de lire cet article : Symfony - Les entités.

<?php

namespace App\Entity;

use App\Repository\ArtistRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=ArtistRepository::class)
 */
class Artist
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private ?string $firstname;

    /**
     * @ORM\OneToMany(targetEntity=Album::class, mappedBy="artist", orphanRemoval=true)
     */
    private ?Collection $albums;

    public function __construct()
    {
        $this->albums = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getFirstname(): ?string
    {
        return $this->firstname;
    }

    public function setFirstname(string $firstname): self
    {
        $this->firstname = $firstname;

        return $this;
    }

    /**
     * @return Collection|Album[]
     */
    public function getAlbums(): Collection
    {
        return $this->albums;
    }

    public function addAlbum(Album $album): self
    {
        if (!$this->albums->contains($album)) {
            $this->albums[] = $album;
            $album->setArtist($this);
        }

        return $this;
    }

    public function removeAlbum(Album $album): self
    {
        if ($this->albums->removeElement($album)) {
            // set the owning side to null (unless already changed)
            if ($album->getArtist() === $this) {
                $album->setArtist(null);
            }
        }

        return $this;
    }
}

Créons maintenant l'entité des albums.

symfony console make:entity Album
# php bin/console make:entity Album

Son contenu :

<?php

namespace App\Entity;

use App\Repository\AlbumRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=AlbumRepository::class)
 */
class Album
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @ORM\ManyToOne(targetEntity=Artist::class, inversedBy="albums")
     * @ORM\JoinColumn(nullable=false)
     */
    private $artist;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getArtist(): ?Artist
    {
        return $this->artist;
    }

    public function setArtist(?Artist $artist): self
    {
        $this->artist = $artist;

        return $this;
    }
}

Les schémas

La création des schémas se fait directement dans le dossier config/graphql/types.
Nous allons créer des fichiers YAML en lien avec nos entités précédentes. Ces fichiers sont une représentation de nos entités de manière que GraphQL sache quel type d'informations retournées.

Artist

Dans le dossier config/graphql/types, créez un fichier Artist.types.yaml contenant le code suivant :

Artist:
    type: object
    config:
        fields:
            id:
                type: 'Int!'
                description: "The unique ID of the artist."
            firstname:
                type: 'String!'
                description: "First name of the artist."
            albums:
                type: '[Album]'
                description: "Albums of the artist."

Vous remarquerez la simplicité de ce fichier qui n'est rien d'autre qu'une description de notre entité.

Notes : la clé album possède le type Album qui est entre crochet pour préciser que nous recevrons un tableau de données, car un artiste est relié à zéro ou plusieurs albums.

Album

Faisons de même avec les albums et créez le fichier Album.types.yaml avec ce contenu :

Album:
    type: object
    config:
        fields:
            id:
                type: 'Int!'
                description: "The unique ID of the album."
            title:
                type: 'String!'
                description: "Title of the album."
            artist:
                type: 'Artist'
                description: "Artist of the album."

Rien de plus simple. La dernière ligne correspond à la relation de table entre Album et Artist.

Notes : la clé artist à pour type Artist qui n'est pas entre crochet, car un album est relié à un seul artiste.

Nos schémas sont dorénavant prêts à être utilisés.