GraphQL use mutation with graphql language #2644

pull/2715/head
Angel Fernando Quiroz Campos 6 years ago
parent 41dc1836fc
commit d456d1b8bc
  1. 2
      config/packages/graphql.yaml
  2. 28
      src/ApiBundle/GraphQL/ApiGraphQLTrait.php
  3. 115
      src/ApiBundle/GraphQL/Map/MutationResolverMap.php
  4. 49
      src/ApiBundle/GraphQL/Mutation/RootMutation.php
  5. 88
      src/ApiBundle/GraphQL/Mutation/UserMutation.php
  6. 45
      src/ApiBundle/GraphQL/Resources/config/Mutation.types.yaml
  7. 25
      src/ApiBundle/GraphQL/Resources/config/schema.types.graphql

@ -2,11 +2,13 @@ overblog_graphql:
definitions:
schema:
query: Query
mutation: Mutation
resolver_maps:
- Chamilo\ApiBundle\GraphQL\Map\RootResolverMap
- Chamilo\ApiBundle\GraphQL\Map\UserResolverMap
- Chamilo\ApiBundle\GraphQL\Map\EnumResolverMap
- Chamilo\ApiBundle\GraphQL\Map\ScalarResolverMap
- Chamilo\ApiBundle\GraphQL\Map\MutationResolverMap
mappings:
types:
-

@ -80,34 +80,6 @@ trait ApiGraphQLTrait
$this->container->get('session')->set('_security_main', serialize($token));
}
/**
* @param string $username
* @param string $password
*
* @return string
*/
private function getUserToken($username, $password): string
{
/** @var User $user */
$user = $this->em->getRepository('ChamiloUserBundle:User')->findOneBy(['username' => $username]);
if (!$user) {
throw new UserError($this->translator->trans('NoUser'));
}
$encoder = $this->container->get('security.password_encoder');
$isValid = $encoder->isPasswordValid(
$user,
$password
);
if (!$isValid) {
throw new UserError($this->translator->trans('InvalidId'));
}
return self::encodeToken($user);
}
/**
* @param User $user
*

@ -0,0 +1,115 @@
<?php
/* For licensing terms, see /license.txt */
namespace Chamilo\ApiBundle\GraphQL\Map;
use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Chamilo\UserBundle\Entity\User;
use GraphQL\Type\Definition\ResolveInfo;
use Overblog\GraphQLBundle\Definition\Argument;
use Overblog\GraphQLBundle\Error\UserError;
use Overblog\GraphQLBundle\Resolver\ResolverMap;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/**
* Class MutationResolverMap.
*
* @package Chamilo\ApiBundle\GraphQL\Map
*/
class MutationResolverMap extends ResolverMap implements ContainerAwareInterface
{
use ApiGraphQLTrait;
/**
* @return array
*/
protected function map()
{
return [
'Mutation' => [
self::RESOLVE_FIELD => function ($value, Argument $args, \ArrayObject $context, ResolveInfo $info) {
$method = 'resolve'.ucfirst($info->fieldName);
return $this->$method($args, $context);
},
],
];
}
/**
* @param Argument $args
*
* @return array
*/
protected function resolveAuthenticate(Argument $args)
{
/** @var User $user */
$user = $this->em->getRepository('ChamiloUserBundle:User')->findOneBy(['username' => $args['username']]);
if (!$user) {
throw new UserError($this->translator->trans('User not found.'));
}
$encoder = $this->container->get('security.password_encoder');
$isValid = $encoder->isPasswordValid($user, $args['password']);
if (!$isValid) {
throw new UserError($this->translator->trans('Password is not valid.'));
}
return [
'token' => $this->encodeToken($user),
];
}
/**
* @param Argument $args
*
* @return array
*/
protected function resolveViewerSendMessage(Argument $args)
{
$this->checkAuthorization();
$currentUser = $this->getCurrentUser();
$usersRepo = $this->em->getRepository('ChamiloUserBundle:User');
$users = $usersRepo->findUsersToSendMessage($currentUser->getId());
$receivers = array_filter(
$args['receivers'],
function ($receiverId) use ($users) {
/** @var User $user */
foreach ($users as $user) {
if ($user->getId() === (int) $receiverId) {
return true;
}
}
return false;
}
);
$result = [];
foreach ($receivers as $receiverId) {
$messageId = \MessageManager::send_message(
$receiverId,
$args['subject'],
$args['text'],
[],
[],
0,
0,
0,
0,
$currentUser->getId()
);
$result[] = [
'receiverId' => $receiverId,
'sent' => (bool) $messageId,
];
}
return $result;
}
}

@ -1,49 +0,0 @@
<?php
/* For licensing terms, see /license.txt */
namespace Chamilo\ApiBundle\GraphQL\Mutation;
use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Overblog\GraphQLBundle\Definition\Argument;
use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface;
use Overblog\GraphQLBundle\Definition\Resolver\MutationInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/**
* Class RootMutation.
*
* @package Chamilo\ApiBundle\GraphQL\Mutation
*/
class RootMutation implements MutationInterface, AliasedInterface, ContainerAwareInterface
{
use ApiGraphQLTrait;
/**
* Returns methods aliases.
*
* For instance:
* array('myMethod' => 'myAlias')
*
* @return array
*/
public static function getAliases()
{
return [
'mutationAuthenticate' => 'authenticate',
];
}
/**
* @param Argument $args
*
* @return array
*/
public function mutationAuthenticate(Argument $args)
{
$token = $this->getUserToken($args['username'], $args['password']);
return [
'token' => $token,
];
}
}

@ -1,88 +0,0 @@
<?php
/* For licensing terms, see /license.txt */
namespace Chamilo\ApiBundle\GraphQL\Mutation;
use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Chamilo\UserBundle\Entity\User;
use Overblog\GraphQLBundle\Definition\Argument;
use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface;
use Overblog\GraphQLBundle\Definition\Resolver\MutationInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/**
* Class UserMutation.
*
* @package Chamilo\ApiBundle\GraphQL\Mutation
*/
class UserMutation implements MutationInterface, AliasedInterface, ContainerAwareInterface
{
use ApiGraphQLTrait;
/**
* Returns methods aliases.
*
* For instance:
* array('myMethod' => 'myAlias')
*
* @return array
*/
public static function getAliases()
{
return [
'mutateSendMessage' => 'user_send_message',
];
}
/**
* @param Argument $args
*
* @return array
*/
public function mutateSendMessage(Argument $args): array
{
$this->checkAuthorization();
$currentUser = $this->getCurrentUser();
$usersRepo = $this->em->getRepository('ChamiloUserBundle:User');
$users = $usersRepo->findUsersToSendMessage($currentUser->getId());
$result = [];
foreach ($args['receivers'] as $receiverId) {
$sentMessage = false;
/** @var User $user */
foreach ($users as $user) {
if ((int) $receiverId === $user->getId()) {
$sentMessage = true;
}
}
$item = [
'receiverId' => $receiverId,
'sent' => false,
];
if ($sentMessage) {
$messageId = \MessageManager::send_message(
$receiverId,
$args['subject'],
$args['text'],
[],
[],
0,
0,
0,
0,
$currentUser->getId()
);
$item['sent'] = (bool) $messageId;
}
$result[] = $item;
}
return $result;
}
}

@ -1,45 +0,0 @@
Mutation:
type: object
config:
fields:
authenticate:
description: "Authenticate user."
type: "AuthenticatePayload!"
args:
username:
type: "String!"
password:
type: "String!"
resolve: "@=mutation('authenticate', [args])"
viewerSendMessage:
description: 'Send messages to user contacts.'
type: '[ViewerSendMessagePayload]!'
args:
receivers:
description: 'Unique IDs of users who will receive the message.'
type: '[Int]!'
subject:
type: 'String!'
text:
type: 'String!'
resolve: "@=mutation('user_send_message', [args, context])"
AuthenticatePayload:
type: object
config:
fields:
token:
description: "Authorization token."
type: "String!"
ViewerSendMessagePayload:
type: object
config:
description: 'The status for each message in queue.'
fields:
receiverId:
description: 'The unique ID for the receiver user.'
type: 'Int!'
sent:
description: "It indicates if the message was or wasn't sent."
type: 'Boolean!'

@ -9,8 +9,33 @@ type Query {
sessionCategory(id: Int!): SessionCategory!
}
type Mutation {
"Authenticate user."
authenticate(username: String!, password: String!): AuthenticatePayload!
"Send messages to user contacts."
viewerSendMessage(
"Unique IDs of users who will receive the message."
receivers: [Int!]!,
subject: String!,
content: String!
): [ViewerSendMessagePayload!]
}
# Objects
type AuthenticatePayload {
"Authorization token."
token: String!
}
"The status for each message in queue."
type ViewerSendMessagePayload {
"The unique ID for the receiver user."
receiverId: Int!
"It indicates if the message was or wasn't sent."
sent: Boolean!
}
"A registered user on the platform."
type User {
"The unique ID of the user."

Loading…
Cancel
Save