core icon indicating copy to clipboard operation
core copied to clipboard

Mixing IRIs between resources and sub-resources when using DTO

Open thomas-cozynergy opened this issue 1 year ago • 0 comments

API Platform version(s) affected: 3.3.2

Description
I try to implement a GraphQL read operation with an output different from the resource and i have a problem with a subressource's IRI id. Doc : https://api-platform.com/docs/core/dto/

In the provider below i put the city with id 10 in the DTO, but in the query's result the city have the id "/books/1" instead of "/cities/10"

How to reproduce
DTO :

final class AnotherBookRepresentationDTO
{
    public int $id;

    public string $name;

    public City $city;
}

Entity:

#[ApiResource(
    graphQlOperations: [
        new Query(
            output: AnotherBookRepresentationDTO::class,
            provider: AnotherBookRepresentationProvider::class,
        ),
    ]
)]
class Book
{
    #[ORM\Column(type: 'integer')]
    #[ORM\Id]
    #[ORM\GeneratedValue(strategy: 'IDENTITY')]
    private int $id;
}

Provider :

final class AnotherBookRepresentationProvider implements ProviderInterface
{
    public function __construct(private EntityManagerInterface $entityManager)
    {
    }
    
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        $dto = new AnotherBookRepresentationDTO();

        $dto->id = 1;
        $dto->name = 'The Book Name';
        $dto->city = $this->entityManager->find(City::class, 10); //Find city with id = 10

        return $dto;
    }
}

Query :

book(id: "/books/1") {
    id
    name
    city {
      id
      zipCode
    }
  }

Result :

{
  "data": {
    "book": {
      "id": "/books/1",
      "name": "The Book Name",
      "city": {
        "id": "/books/1",  //Problem is here: id should be "/cities/10"
        "zipCode": "40100"
      }
    }
  }
}

thomas-cozynergy avatar May 17 '24 15:05 thomas-cozynergy