Skip to content

GraphQL requires a unified hydrator to convert Interfaces to Arrays #36779

Open
@ioweb-gr

Description

@ioweb-gr

Summary

I've been working on a project that requires a lot of new GraphQL endpoints for various purposes, and while digging around in the core endpoints to simulate behaviour I noticed that every Resolver is returning an array of data but they don't build the array in a similar way.

Unlike REST Api where there's a unified way to declare the endpoints, and by returning an Interface you can get the correct data in your endpoint result, in GraphQL you have to build everything from scratch and compile the array you want even if you want to return products or categories or customer info or any other well defined entity with a REST Api already configured.

Examples

Consider this query

type Query {
    recentlyBoughtProducts(
        pageSize: Int = 10,
    ): RecentlyBoughtProductsData
}

type RecentlyBoughtProductsData {
    items: [ProductInterface]
    totalCount: Int
}

In the resolver in order to return the ProductInterface we have to add an array like this

      foreach ($items as $item) {
            $productData = $item->toArray();
            $productData['model'] = $item;
            $result[] = $productData;
        }

Similar to how it's built on the original endpoints
However no one will remember that in the productData they have to set the 'model' key. It only comes after you see the exception.

But for example to return a CustomerInterface I can just use

\Magento\Framework\EntityManager\HydratorInterface

like this

$result = $this->hydrator->extract($customer);

In other core entities, the HydratorInterface won't even process them though and they don't have a toArray() function.

So there's no unified way to build GraphQL endpoints and follow the same practice to get a result.

Proposed solution

In my opinion there should be a Hydrator class similar to the original that can handle conversion of any proper Interface to the proper array that GraphQL expects, similar to how the REST API will expose the item through well-defined getters and setters.

If it's not feasible could you explain why?

Release note

No response

Triage and priority

  • Severity: S0 - Affects critical data or functionality and leaves users without workaround.
  • Severity: S1 - Affects critical data or functionality and forces users to employ a workaround.
  • Severity: S2 - Affects non-critical data or functionality and forces users to employ a workaround.
  • Severity: S3 - Affects non-critical data or functionality and does not force users to employ a workaround.
  • Severity: S4 - Affects aesthetics, professional look and feel, “quality” or “usability”.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions