访问根值和参数解析器graphql-php

时间:2017-10-19 21:57:43

标签: php graphql graphql-php

我在使用graphql-php库的代码的以下部分时遇到问题。

'resolve' =>function($value,$args,$context)

当我运行查询时:

"http://localhost:8080/index.php?query={certificate(id:"123ecd"){id}}" 

我收到以下列出的消息:

{"errors":[{"message":"Internal server error","category":"internal",
"locations":[{"line":1,"column":2}],"path":["certificate"]}],"data":{"certificate":null}}

其次,当我运行嵌套查询时

"http://192.168.211.15:8080/index.php?query{certificates{id,products{id}}}"

我得到以下列出的回复:

{"errors":[{"message":"Internal server error","category":"internal","locations":[{"line":1,"column":26}],"path":["certificates",0,"products"]}
"data":{"certificates":[{"id":"a023gavcx","status":"Valid","products":null}]}}

以下是我的完整代码:

  use GraphQL\Type\Definition\ObjectType;
  use GraphQL\Type\Definition\ResolveInfo;
  class CertificateType extends ObjectType{
  public function __construct(){
         $config = [
              'name' => 'Certificate',
              'fields' => function() {
                return [
                        'id' => [
                                'type' => Types::nonNull(Types::string()),
                            ],
                            'number' => [
                                'type' => Types::int()
                            ],
                            'first_issue_date' => [
                                'type' => Types::string() 
                            ],
                            'products' => [
                               'type' => Types::product(),

                            'resolve'=> function($value, $args, $context){
                               $pdo = $context['pdo'];
                               $cert_id = $value->id;

                               $result = $pdo->query("select * from products where cert_id = {$cert_id} ");
                               return $result->fetchObject() ?: null;     
                            }    
                          ]


                        ];
                    }

                ];
                parent::__construct($config);
            }

        }


 use GraphQL\Type\Definition\Type;

     class Types extends Type{

        protected static $typeInstances = [];

        public static function certificate(){
                return static::getInstance(CertificateType::class);
        }

        public static function product(){
                return static::getInstance(ProductType::class);
        }

        protected static function getInstance($class, $arg = null){
                    if (!isset(static::$typeInstances[$class])) {
                            $type = new $class($arg);
                         static::$typeInstances[$class] = $type;
                    }
                    return static::$typeInstances[$class];
                }
        }

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;

class ProductType extends ObjectType
    {
        public function __construct()
        {
            $config = [
                'name' => 'Product',
                'fields' => function() {
                    return [
                        'id' => [
                            'type' => Types::nonNull(Types::string()),
                        ],                        
                        'primary_activity' => [
                            'type' => Types::string()
                        ],
                        'trade_name' => [
                            'type' => Types::string()
                        ],
                    ];
                },
            ];
            parent::__construct($config);
        }

    }


   require_once __DIR__ . '/../../../../autoload.php';
   use GraphQL\GraphQL;
   use GraphQL\Type\Schema;
   use GraphQL\Type\Definition\ObjectType;
   use GraphQL\Type\Definition\Type;

   define('BASE_URL', 'http://127.0.0.1:8080');

   ini_set('display_errors', 0);


   $debug = !empty($_GET['debug']);
   if ($debug) {
        $phpErrors = [];
        set_error_handler(function($severity, $message, $file, $line) use (&$phpErrors) {
            $phpErrors[] = new ErrorException($message, 0, $severity, $file, $line);
            });
        }     
        try { 
            $dbHost = 'localhost';
                $dbName  = '*******';
                $dbUsername = 'root';
                $dbPassword = '*********';

            $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName}", $dbUsername, $dbPassword);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $appContext = [
                'pdo' => $pdo  ];

            if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
                $raw = file_get_contents('php://input') ?: '';
                $data = json_decode($raw, true);
            } else {

                $data = $_REQUEST;
            }

            $data += ['query' => null, 'variables' => null];

            if (null === $data['query']) {

                $data['query'] = '{hello}';
            }
            require __DIR__ . '/types/CertificateType.php';
            require __DIR__ . '/types/ProductType.php';
            require __DIR__ . '/types/OrganizationType.php';

            require __DIR__ . '/Types.php';

            $queryType = new ObjectType([
                'name' => 'Query',
                'fields' => [
                'hello' => [
                        'description' => ' Hello world',
                        'type' => Types::string(),
                        'resolve' => function() {
                        return 'Hello World';
                        }
                     ],
                   'certificate' => [
                                'type' => Types::listOf(Types::certificate()),
                                'description' => 'This is the certificate identification',
                                'args' => [ 
                                           'id' => Types::string()],
                                'resolve' => function ($rootValue,$args,$context) {
                                     $pdo = $context['pdo'];
                                     $id = $args['id'];

                                    return $pdo->query("SELECT * from certificates where  id ={$id}");
                                   return $data->fetchObject() ?: null;
                                }
                    ],
                        'certificates' => [
                        'type' => Types::listOf(Types::certificate()),
                        'resolve' => function($rootValue, $args, $context) {
                        $pdo = $context['pdo'];
                        $result = $pdo->query("select * from certificates  order by id  limit 10");
                        return $result->fetchAll(PDO::FETCH_OBJ);
                        }
                    ],  

                ]
            ]);

            $schema = new Schema([
                'query' => $queryType
            ]);

            $result = GraphQL::execute(
                $schema,
                $data['query'],
                null,
                $appContext,
                (array) $data['variables']
            );

            if ($debug && !empty($phpErrors)) {
                $result['extensions']['phpErrors'] = array_map(
                    ['GraphQL\Error\FormattedError', 'createFromPHPError'],
                    $phpErrors
                );
            }
            $httpStatus = 200;
        } catch (\Exception $error) {
            //  Handling Exception
            // *************************************
            $httpStatus = 500;
            if (!empty($_GET['debug'])) {
                $result['extensions']['exception'] = FormattedError::createFromException($error);
            } else {
                $result['errors'] = [FormattedError::create('Unexpected Error')];
            }
        }

        header('Content-Type: application/json', true, $httpStatus);
        echo json_encode($result);

有人可以帮我解决这些问题。提前致谢

0 个答案:

没有答案