登录/注册

GraphQL

GraphQL 组件对 thecodingmachine/graphqlite 进行抽象。

安装

composer require hyperf/graphql

快速开始

简单查询

<?php

namespace AppController;

use GraphQLGraphQL;
use GraphQLTypeSchema;
use HyperfDiAnnotationInject;
use HyperfGraphQLAnnotationQuery;
use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationPostMapping;
use HyperfHttpServerContractRequestInterface;

/**
 * @Controller()
 */
class GraphQLController
{
    /**
     * @Inject()
     * @var Schema
     */
    protected $schema;

    /**
     * @PostMapping(path="/graphql")
     */
    public function test(RequestInterface $request)
    {
        $rawInput = $request->getBody()->getContents();
        $input = json_decode($rawInput, true);
        $query = $input['query'];
        $variableValues = isset($input['variables']) ? $input['variables'] : null;
        return GraphQL::executeQuery($this->schema, $query, null, null, $variableValues)->toArray();
    }

    /**
     * @Query()
     */
    public function hello(string $name): string
    {
        return $name;
    }
}

查询:

{
    hello(name: "graphql")
}

响应:

{
    "data": {
        "hello": "graphql"
    }
}

类型映射

<?php
namespace AppModel;

use HyperfGraphQLAnnotationType;
use HyperfGraphQLAnnotationField;

/**
 * @Type()
 */
class Product
{
    protected $name;
    protected $price;

    public function __construct(string $name, float $price)
    {
        $this->name = $name;
        $this->price = $price;
    }

    /**
     * @Field()
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @Field()
     */
    public function getPrice(): ?float
    {
        return $this->price;
    }
}

GraphQLController 中加入

<?php
use AppModelProduct;

/**
 * @Query()
 */
public function product(string $name, float $price): Product
{
    return new Product($name, $price);
}

查询:

{
    hello(name: "graphql")
    product(name: "goods", price: 156.5) {
        name
        price
    }
}

响应:

{
    "data": {
        "hello": "graphql",
        "product": {
            "name": "goods",
            "price": 156.5
        }
    }
}

更多使用方法可以查看 GraphQLite 的文档。

原文地址:https://www.bookstack.cn/read/hyperf-1.1.20/graphql.md
文章来源与用户投稿或网络采集,如果您是本文的作者,发现版权或转载方式问题请右侧邮箱联系管理员。

抢沙发

我们不是孤独的个体,留下足迹,保持联系,成为团体...
姓名
电子邮件
个人主页