使用GraphQL+Lighthouse(+Laravel)进行API开发1(安装方法和配置篇)

我們決定在現有使用Laravel操作的系統中新增一個API,並採用GraphQL來實現。

使用GraphQL的主要原因是由于页面的特性,如果使用REST形式来实现,API调用的频率会增加。我们可以将所有响应实现为一个入口点,然后通过查询参数进行过滤,但与其费力地实现复杂的方式,不如选择使用GraphQL来简洁地实现。

除去形式上的原因之外,坦白说,我最大的原因是想尝试一下GraphQL。笑

这篇文章计划跨越多个部分,以下是预定的标题。

    1. 在GraphQL+Lighthouse(+Laravel)中进行API开发1(安装方法和配置)

 

    1. 在GraphQL+Lighthouse(+Laravel)中进行API开发2(开发篇1-非Eloquent模型的实现)

 

    1. 在GraphQL+Lighthouse(+Laravel)中进行API开发3(开发篇2-错误处理)

 

    在GraphQL+Lighthouse(+Laravel)中进行API开发4(功能测试篇)

我們大致上進行了安裝、開發和測試,所以我們打算在這個過程中留下所獲取的知識。

用于PHP开发的GraphQL库们

在实现用于Laravel的GraphQL应用程序时,有几个库可供使用。
GraphQL官方网站介绍了以下两个库。(截至2019年01月31日)

    • graphql-php

 

    graphql-relay-php

参考资料)介绍GraphQL官方网站上的库

另外,这个也似乎是受欢迎的 Laravel 兼容选项。

    laravel-graphql

然而,这次选择采用了Lighthouse是因为它具有类似于GraphQL的类型定义和模式定义的特点,而且文档也很好。需要注意的是Lighthouse是依赖于graphql-php的。

建造过程

我使用以下步骤建立了Laravel的本地开发环境。
使用Docker构建多个Laravel 5.5项目的环境设置(1)
使用Docker构建多个Laravel 5.5项目的环境设置(2)
在假设Laravel的运行环境已经准备好的前提下,我们将继续讨论。

通过composer引入lighthouse

composer require nuwave/lighthouse

# docker環境の場合
docker-compose run --rm hoge_composer require nuwave/lighthouse

2. 生成schema文件

php artisan vendor:publish --provider="Nuwave\Lighthouse\Providers\LighthouseServiceProvider" --tag=schema

# docker環境の場合
dc exec hoge php artisan vendor:publish --provider="Nuwave\Lighthouse\Providers\LighthouseServiceProvider" --tag=schema

然后,将生成一个名为routes/graphql/schema.graphql的文件,其中包含了Query和Mutation等的实现示例。

3.安装调试工具。

有几个用于检查GraphQL查询的调试工具可供使用。其中,例如grapiql等是比较著名的。这次我们将安装在lighthouse官方网站上介绍的laravel-graphql-playground。

composer require --dev mll-lab/laravel-graphql-playground

# docker環境の場合
docker-compose run --rm hoge_composer require --dev mll-lab/laravel-graphql-playground

我們在官方網站上建議安裝時將其放入 composer 的 require 中,但為了避免在正式環境中安裝額外的內容,我們決定指定 –dev 選項。

4. 创建适用于lighthouse的设置文件。

php artisan vendor:publish --provider="Nuwave\Lighthouse\Providers\LighthouseServiceProvider" --tag=config

# docker環境の場合
dc exec hoge php artisan vendor:publish --provider="Nuwave\Lighthouse\Providers\LighthouseServiceProvider" --tag=config

执行此命令将生成名为config/lighthouse.php的文件。该文件允许更改入口点、指定用于graphql入口点请求的中间件、指定自定义错误处理程序等。

我認為基本上使用默認設定應該沒有問題。
請您確認我在每個項目上附上的評論。

<?php

use GraphQL\Error\Debug;
use GraphQL\Validator\Rules\DisableIntrospection;

return [
    /*
    |--------------------------------------------------------------------------
    | GraphQL endpoint
    |--------------------------------------------------------------------------
    |
    | Set the endpoint to which the GraphQL server responds.
    | The default route endpoint is "yourdomain.com/graphql".
    |
    */
    // xxxx.com/graphqlがエンドポイントとなる
    'route_name' => 'graphql', 

    /*
    |--------------------------------------------------------------------------
    | Enable GET requests
    |--------------------------------------------------------------------------
    |
    | This setting controls if GET requests to the GraphQL endpoint are allowed.
    |
    */
    // getリクエストを許容
    'route_enable_get' => true,

    /*
    |--------------------------------------------------------------------------
    | Route configuration
    |--------------------------------------------------------------------------
    |
    | Additional configuration for the route group.
    | Check options here https://lumen.laravel.com/docs/routing#route-groups
    |
    | Beware that middleware defined here runs before the GraphQL execution phase.
    | This means that errors will cause the whole query to abort and return a
    | response that is not spec-compliant. It is preferable to use directives
    | to add middleware to single fields in the schema.
    | Read more about this in the docs https://lighthouse-php.netlify.com/docs/auth.html#apply-auth-middleware
    |
    */
    'route' => [
        'prefix' => '',
        // middlewareのグループ指定
        // 上のコメントではこちらでミドルウェアを指定するとgraphqlの処理よりも前にミドルウェアが実行されるため、
        // エラーが発生した場合graphqlの仕様に沿ったレスポンスが返せないと警告しています。
        // 可能であればschemaファイル(schema.graphql)内で@middlewareディレクティブを用いて
        // クエリ毎にミドルウェアを指定してgraphql処理→ミドルウェアチェック
        // 順で実行することを推奨しているようです。
        // 'middleware' => ['loghttp']
    ],

    /*
    |--------------------------------------------------------------------------
    | Schema declaration
    |--------------------------------------------------------------------------
    |
    | This is a path that points to where your GraphQL schema is located
    | relative to the app path. You should define your entire GraphQL
    | schema in this file (additional files may be imported).
    |
    */
    'schema' => [
        'register' => base_path('routes/graphql/schema.graphql'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Schema Cache
    |--------------------------------------------------------------------------
    |
    | A large part of the Schema generation is parsing into an AST.
    | This operation is pretty expensive so it is recommended to enable
    | caching in production mode.
    |
    */
    'cache' => [
        'enable' => env('LIGHTHOUSE_CACHE_ENABLE', false),
        'key' => env('LIGHTHOUSE_CACHE_KEY', 'lighthouse-schema'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Directives
    |--------------------------------------------------------------------------
    |
    | List directories that will be scanned for custom server-side directives.
    |
    */
    'directives' => [__DIR__.'/../app/Http/GraphQL/Directives'],

    /*
    |--------------------------------------------------------------------------
    | Namespaces
    |--------------------------------------------------------------------------
    |
    | These are the default namespaces where Lighthouse looks for classes
    | that extend functionality of the schema.
    |
    */
    'namespaces' => [
        'models' => 'App\\Models',
        'queries' => 'App\\Http\\GraphQL\\Queries',
        'mutations' => 'App\\Http\\GraphQL\\Mutations',
        'interfaces' => 'App\\Http\\GraphQL\\Interfaces',
        'unions' => 'App\\Http\\GraphQL\\Unions',
        'scalars' => 'App\\Http\\GraphQL\\Scalars',
    ],

    /*
    |--------------------------------------------------------------------------
    | Security
    |--------------------------------------------------------------------------
    |
    | Control how Lighthouse handles security related query validation.
    | This configures the options from http://webonyx.github.io/graphql-php/security/
    | A setting of "0" means that the validation rule is disabled.
    |
    */
    'security' => [
        'max_query_complexity' => 0,
        'max_query_depth' => 0,
        'disable_introspection' => DisableIntrospection::DISABLED,
    ],

    /*
    |--------------------------------------------------------------------------
    | Debug
    |--------------------------------------------------------------------------
    |
    | Control the debug level as described in http://webonyx.github.io/graphql-php/error-handling/
    | Debugging is only applied if the global Laravel debug config is set to true.
    |
    */
    // debugモードの指定
    // こちらがonとなるとエラー時のstack traceなどの情報がエラーメッセージとして返されます。
    // 内部的にLaravelの.env内の環境変数APP_DEBUG=trueを見ていますので、本番環境では必ずfalseにしておきましょう。
    'debug' => Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE,

    /*
    |--------------------------------------------------------------------------
    | Error Handlers
    |--------------------------------------------------------------------------
    |
    | Register error handlers that receive the Errors that occur during execution and
    | handle them. You may use this to log, filter or format the errors.
    | The classes must implement Nuwave\Lighthouse\Execution\ErrorHandler
    |
    */
    // lighthouseのエラーハンドラーです。基本的にはこちらのエラーハンドラーで必要十分です。詳細はエラーハンドル編で記載します。
    'error_handlers' => [
        \Nuwave\Lighthouse\Execution\ExtensionErrorHandler::class,
    ],

    /*
    |--------------------------------------------------------------------------
    | Extensions
    |--------------------------------------------------------------------------
    |
    | Register extension classes that extend \Nuwave\Lighthouse\Schema\Extensions\GraphQLExtension
    |
    */
    'extensions' => [
        // \Nuwave\Lighthouse\Schema\Extensions\TracingExtension::class
    ],

     /*
     |--------------------------------------------------------------------------
     | GraphQL Controller
     |--------------------------------------------------------------------------
     |
     | Specify which controller (and method) you want to handle GraphQL requests.
     |
     */
    'controller' => 'Nuwave\Lighthouse\Support\Http\Controllers\GraphQLController@query',

    /*
    |--------------------------------------------------------------------------
    | Global ID
    |--------------------------------------------------------------------------
    |
    | The name that is used for the global id field on the Node interface.
    | When creating a Relay compliant server, this must be named "id".
    |
    */
    'global_id_field' => 'id',

    /*
    |--------------------------------------------------------------------------
    | Batched Queries
    |--------------------------------------------------------------------------
    |
    | GraphQL query batching means sending multiple queries to the server in one request,
    | You may set this flag to process/deny batched queries.
    |
     */
    'batched_queries' => true,
];

这次我在我的页面内实现了API。由于现有系统在中间件中实现了认证,所以所有请求都需要经过用户认证的中间件。因此,尽管这是不推荐的方法,我指定了一个名为’mypage_middleware’的中间件组作为mypage的中间件。在lighthouse中,使用@middleware指令基本上是先执行返回响应的处理,然后再执行中间件进行检查的实现方式。

接下来我们将从本次环境搭建开始介绍实际进行 GraphQL 服务器端开发的步骤。本次讲解到此结束。

广告
将在 10 秒后关闭
bannerAds