Skip to content

How to change field return type in middleware #828

Description

@mvarendorff

For a new requirement, I am trying to add an additional type as union to the existing results, i.e. if the code says that a mutation resolver returns FooPayload, I want the schema to say that resolver returns FooPayload | BarPayload. How would I best go about this?

I discovered FieldMiddlewareInterface and my initial instinct was to do something like akin to this

final readonly class ValidationResultFieldMiddleware implements FieldMiddlewareInterface
{
    public function __construct(
        private RecursiveTypeMapperInterface $typeMapper,
        private NamingStrategyInterface $namingStrategy,
    ) {}

    public function process(
        QueryFieldDescriptor $queryFieldDescriptor,
        FieldHandlerInterface $fieldHandler,
    ): ?FieldDefinition {
        $oldType = $queryFieldDescriptor->getType();
        $barPayloadType = $this->typeMapper->mapNameToType('BarPayload');

        $typeUnion = new UnionType([$oldType, $errorListType], $this->typeMapper, $this->namingStrategy);
        $newFieldDescriptor = $queryFieldDescriptor->withType($typeUnion);

        return $fieldHandler->handle($newFieldDescriptor);
    }
}

however this fails in our Symfony setup because no service of type RecursiveTypeMapperInterface is registered. I tried various combinations of TypeMappers but could not find any that were registered. I also tried my luck with TypeMapperFactory however that in turn requires me to have access to an instance of FactoryContext which I don't have either.

Am I on the completely wrong track here? Is this even possible or intended to be possible presently?

A little context as to what I am trying to achieve: We recently quite painfully learned that our current validation concept is not valid per the GraphQL Spec (long story...) and we now landed on wanting to return validation errors as part of the payload as a potential path forward. For that, I am to prototype how to centralize this process to avoid having validation logic explicitly present on each of several dozen mutation resolvers, this experiment being one of them.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions