folklore/graphql

此包已被废弃,不再维护。没有建议替代包。

Facebook GraphQL for Laravel

v1.1.0 2018-04-23 22:33 UTC

README

此包不再维护。请使用 rebing/graphql-laravel 或其他 Laravel GraphQL 包。

使用 Facebook GraphQL 与 Laravel 5 或 Lumen。它基于此处的 PHP 实现 here。您可以在 React 博客上的 GraphQL Introduction 中找到更多关于 GraphQL 的信息,或您还可以阅读 GraphQL 规范。这是一个正在进行中的项目。

此包与 Eloquent 模型(或任何其他数据源)兼容。请参阅下面的示例。

Latest Stable Version Build Status Total Downloads

要使用 laravel-graphql 与 Relay,请检查 feature/relay 分支。

安装

已发布版本 1.0。如果您是从旧版本升级,您可以在 升级到 1.0 中进行检查。

依赖

1- 在您的 composer.json 文件中通过 Composer 引入此包。

{
  "require": {
    "folklore/graphql": "~1.0.0"
  }
}

2- 运行 Composer 安装或更新新要求。

$ composer install

或者

$ composer update

Laravel >= 5.5.x

1- 发布配置文件

$ php artisan vendor:publish --provider="Folklore\GraphQL\ServiceProvider"

2- 查看配置文件

config/graphql.php

Laravel <= 5.4.x

1- 将服务提供者添加到您的 config/app.php 文件

Folklore\GraphQL\ServiceProvider::class,

2- 将外观添加到您的 config/app.php 文件

'GraphQL' => Folklore\GraphQL\Support\Facades\GraphQL::class,

3- 发布配置文件

$ php artisan vendor:publish --provider="Folklore\GraphQL\ServiceProvider"

4- 查看配置文件

config/graphql.php

Lumen

1-bootstrap/app.php 中加载服务提供者

$app->register(Folklore\GraphQL\LumenServiceProvider::class);

2- 为了使用外观,您需要在 bootstrap/app.php 中取消注释行 $app->withFacades();

取消注释此行后,您将启用 GraphQL 外观

$app->withFacades();

3- 发布配置文件

$ php artisan graphql:publish

4-bootstrap/app.php 中加载配置文件

重要:此命令必须在注册服务提供者之前执行

$app->configure('graphql');
...
$app->register(Folklore\GraphQL\LumenServiceProvider::class)

5- 查看配置文件

config/graphql.php

文档

使用方法

高级使用

模式

从版本 1.0 开始,您可以定义多个模式。如果有多个模式可能很有用,例如,您想要一个公共端点和另一个需要身份验证的端点。

您可以在配置中定义多个模式

'schema' => 'default',

'schemas' => [
    'default' => [
        'query' => [
            //'users' => 'App\GraphQL\Query\UsersQuery'
        ],
        'mutation' => [
            //'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
        ]
    ],
    'secret' => [
        'query' => [
            //'users' => 'App\GraphQL\Query\UsersQuery'
        ],
        'mutation' => [
            //'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
        ]
    ]
]

或者您可以使用外观添加模式

GraphQL::addSchema('secret', [
    'query' => [
        'users' => 'App\GraphQL\Query\UsersQuery'
    ],
    'mutation' => [
        'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
    ]
]);

之后,您可以使用外观构建模式

// Will return the default schema defined by 'schema' in the config
$schema = GraphQL::schema();

// Will return the 'secret' schema
$schema = GraphQL::schema('secret');

// Will build a new schema
$schema = GraphQL::schema([
    'query' => [
        //'users' => 'App\GraphQL\Query\UsersQuery'
    ],
    'mutation' => [
        //'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
    ]
]);

或者您可以为特定模式请求端点

// Default schema
http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}

// Secret schema
http://homestead.app/graphql/secret?query=query+FetchUsers{users{id,email}}

创建查询

首先您需要创建一个类型。

namespace App\GraphQL\Type;

use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;

class UserType extends GraphQLType
{
    protected $attributes = [
        'name' => 'User',
        'description' => 'A user'
    ];

    /*
    * Uncomment following line to make the type input object.
    * https://graphql.net.cn/learn/schema/#input-types
    */
    // protected $inputObject = true;

    public function fields()
    {
        return [
            'id' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The id of the user'
            ],
            'email' => [
                'type' => Type::string(),
                'description' => 'The email of user'
            ]
        ];
    }

    // If you want to resolve the field yourself, you can declare a method
    // with the following format resolve[FIELD_NAME]Field()
    protected function resolveEmailField($root, $args)
    {
        return strtolower($root->email);
    }
}

将类型添加到配置文件 config/graphql.php

'types' => [
    'User' => 'App\GraphQL\Type\UserType'
]

您也可以通过外观,例如在服务提供者中添加类型。

GraphQL::addType('App\GraphQL\Type\UserType', 'User');

然后您需要定义一个返回此类型(或列表)的查询。您还可以指定在 resolve 方法中使用的参数。

namespace App\GraphQL\Query;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Query;
use App\User;

class UsersQuery extends Query
{
    protected $attributes = [
        'name' => 'users'
    ];

    public function type()
    {
        return Type::listOf(GraphQL::type('User'));
    }

    public function args()
    {
        return [
            'id' => ['name' => 'id', 'type' => Type::string()],
            'email' => ['name' => 'email', 'type' => Type::string()]
        ];
    }

    public function resolve($root, $args)
    {
        if (isset($args['id'])) {
            return User::where('id' , $args['id'])->get();
        } else if(isset($args['email'])) {
            return User::where('email', $args['email'])->get();
        } else {
            return User::all();
        }
    }
}

将查询添加到配置文件 config/graphql.php

'schemas' => [
    'default' => [
        'query' => [
            'users' => 'App\GraphQL\Query\UsersQuery'
        ],
        // ...
    ]
]

就这样。您应该能够在 URL /graphql(或您在配置中选择的任何内容)上进行请求以查询 GraphQL。尝试以下 query 输入的 GET 请求

query FetchUsers {
  users {
    id
    email
  }
}

例如,如果您使用 homestead

http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}

创建突变

突变就像任何其他查询一样,它接受参数(将用于执行突变)并返回特定类型的对象。

例如,更新用户密码的突变。首先您需要定义突变。

namespace App\GraphQL\Mutation;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Mutation;
use App\User;

class UpdateUserPasswordMutation extends Mutation
{
    protected $attributes = [
        'name' => 'updateUserPassword'
    ];

    public function type()
    {
        return GraphQL::type('User');
    }

    public function args()
    {
        return [
            'id' => ['name' => 'id', 'type' => Type::nonNull(Type::string())],
            'password' => ['name' => 'password', 'type' => Type::nonNull(Type::string())]
        ];
    }

    public function resolve($root, $args)
    {
        $user = User::find($args['id']);

        if (!$user) {
            return null;
        }

        $user->password = bcrypt($args['password']);
        $user->save();

        return $user;
    }
}

resolve 方法中所示,您使用参数更新模型并返回它。

然后,您将突变添加到配置文件 config/graphql.php

'schema' => [
    'default' => [
        'mutation' => [
            'updateUserPassword' => 'App\GraphQL\Mutation\UpdateUserPasswordMutation'
        ],
        // ...
    ]
]

您应该能够在端点上使用以下查询执行突变。

mutation users {
  updateUserPassword(id: "1", password: "newpassword") {
    id
    email
  }
}

如果您使用 homestead

http://homestead.app/graphql?query=mutation+users{updateUserPassword(id: "1", password: "newpassword"){id,email}}

向突变添加验证

可以向突变添加验证规则。它使用 laravel 的 Validatorargs 执行验证。

在创建突变时,您可以通过以下方式添加定义应用验证规则的方法

namespace App\GraphQL\Mutation;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Mutation;
use App\User;

class UpdateUserEmailMutation extends Mutation
{
    protected $attributes = [
        'name' => 'UpdateUserEmail'
    ];

    public function type()
    {
        return GraphQL::type('User');
    }

    public function args()
    {
        return [
            'id' => ['name' => 'id', 'type' => Type::string()],
            'email' => ['name' => 'email', 'type' => Type::string()]
        ];
    }

    public function rules()
    {
        return [
            'id' => ['required'],
            'email' => ['required', 'email']
        ];
    }

    public function resolve($root, $args)
    {
        $user = User::find($args['id']);

        if (!$user) {
            return null;
        }

        $user->email = $args['email'];
        $user->save();

        return $user;
    }
}

或者您可以定义每个参数的规则

class UpdateUserEmailMutation extends Mutation
{
    //...

    public function args()
    {
        return [
            'id' => [
                'name' => 'id',
                'type' => Type::string(),
                'rules' => ['required']
            ],
            'email' => [
                'name' => 'email',
                'type' => Type::string(),
                'rules' => ['required', 'email']
            ]
        ];
    }

    //...
}

当您执行突变时,它将返回验证错误。由于 GraphQL 规范定义了错误的一定格式,验证错误消息被添加到错误对象作为额外的 validation 属性。要找到验证错误,您应该检查具有 message 等于 'validation' 的错误,然后 validation 属性将包含由 Laravel Validator 返回的正常错误消息。

{
  "data": {
    "updateUserEmail": null
  },
  "errors": [
    {
      "message": "validation",
      "locations": [
        {
          "line": 1,
          "column": 20
        }
      ],
      "validation": {
        "email": [
          "The email is invalid."
        ]
      }
    }
  ]
}