I have tried to make delete functionality with graphQL and php. I am using this library:
https://github.com/webonyx/graphql-php
It has examples, but it does not have mutations example. I tried to create mutation class on my own and it works ok.
The create and update looks ok, but delete looks non standard, but still works. Can you tell is this completely bad or not? And if it is, then how it should look like? Maybe you can give some good tutorial about this.
class MutationType extends ObjectType
{
protected $serviceManager;
public function __construct($serviceManager)
{
$config = [
'name' => 'Mutation',
'fields' => [
'person' => [
'type' => Types::person(),
'description' => 'Returns person by id',
'args' => [
'firstName' => Types::string(),
'id' => Type::int(),
]
],
'deletePerson' => [
'type' => Types::person(),
'args' => [
'id' => Type::int(),
]
],
],
'resolveField' => function($val, $args, $context, ResolveInfo $info) {
return $this->{$info->fieldName}($val, $args, $context, $info);
}
];
$this->serviceManager = $serviceManager ;
parent::__construct($config);
}
public function person($rootValue, $args)
{
$personTable = $this->serviceManager->get(PersonTable::class);
$person = new Person();
$person->firstName = $args['firstName'];
if (isset($args['id'])) {
$person->id = $args['id'];
}
return $personTable->savePerson($person);
}
public function deletePerson($rootValue, $args)
{
$personTable = $this->serviceManager->get(PersonTable::class);
return $personTable->deletePerson($args['id']);
}
}
As you can see there is fields array. One item is person, for creating and updating. And another field is deletePerson.
deletePerson has a type, which is not useful. After we delete a person, we do not return person. But it was required key, otherwise I get error.
And here is the part of the code from Zend 2 controller method which uses the mutation type, but you do not need to pay much attention to it I guess:
$queryType = $this->getServiceLocator()->get('Application\GraphQL\Type\QueryType');
$mutationType = $this->getServiceLocator()->get('Application\GraphQL\Type\MutationType');
// GraphQL schema to be passed to query executor:
$schema = new Schema([
'query' => $queryType,
'mutation' => $mutationType
]);
$result = GraphQL::execute(
$schema,
$data['query'],
null,
$appContext,
(array) $data['variables']
);