'api platform with graphQL support
Just started to work with api platform with graphQl support enabled. If I understand correctly with graphQl I don't need to create routes like we need with REST, the endpoints are created in the frontend from the Model schemas.
But what if I have a method which had some logic in it and I need to run that code? If I dont have a route I can't execute that. What can I do than?
Thanks for the answers in advance. Br
Solution 1:[1]
You can solve that by using custom queries to fetch data or custom mutations to post/put/delete data in REST terms.
You question implies you want to have a custom mutation, according to the docs this would work like this:
Create your resolver:
<?php
namespace App\Resolver;
use ApiPlatform\Core\GraphQl\Resolver\MutationResolverInterface;
use App\Model\Book;
final class BookMutationResolver implements MutationResolverInterface
{
/**
* @param Book|null $item
*
* @return Book
*/
public function __invoke($item, array $context)
{
// Mutation input arguments are in $context['args']['input'].
// Do something with the book.
// Or fetch the book if it has not been retrieved.
// The returned item will pe persisted.
return $item;
}
}
then use this custom mutation as following:
<?php
namespace App\Model;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Resolver\BookMutationResolver;
#[ApiResource(
graphql: [
// Auto-generated queries and mutations
'item_query',
'collection_query',
'create',
'update',
'delete',
'mutation' => [
'mutation' => BookMutationResolver::class
],
'withCustomArgsMutation' => [
'mutation' => BookMutationResolver::class,
'args' => [
'sendMail' => ['type' => 'Boolean!', 'description'=> 'Send a mail?' ]
]
],
'disabledStagesMutation' => [
'mutation' => BookMutationResolver::class,
'deserialize' => false,
'write' => false
]
]
)]
class Book
{
// ...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexander Kludt |
