aarab/laravel-graphql-playground

轻松将 GraphQL Playground 集成到您的 Laravel 项目中

v1.0.0 2024-03-25 11:01 UTC

This package is auto-updated.

Last update: 2024-09-25 12:13:15 UTC


README

已弃用

该项目已弃用,建议使用 https://github.com/mll-lab/laravel-graphiql

轻松将 GraphQL Playground 集成到您的 Laravel 项目中。

GitHub license Packagist Packagist

请注意:这不是一个 GraphQL 服务器实现,而是一个用于测试和探索您模式的用户界面。对于服务器组件,我们推荐使用 nuwave/lighthouse

安装

composer require aarab/laravel-graphql-playground

如果您正在使用 Lumen,请在 bootstrap/app.php 中注册服务提供者

$app->register(MLL\GraphQLPlayground\GraphQLPlaygroundServiceProvider::class);

配置

默认情况下,Playground 可在 /graphql-playground 访问,并假定有一个运行在 /graphql 的 GraphQL 端点。

要更改默认设置,使用以下命令发布配置

php artisan vendor:publish --tag=graphql-playground-config

您将在 config/graphql-playground.php 找到配置文件。

Lumen

如果您正在使用 Lumen,请手动将其复制到该位置,并在您的 boostrap/app.php 中加载配置

$app->configure('graphql-playground');

通过代理使用 HTTPS

如果您的应用程序位于解析 https 的代理后面,端点生成的 URL 可能不会使用 https://,因此默认情况下 Playground 可能无法正常工作。为了解决这个问题,请配置您的 TrustProxies 中间件以包含 \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_FOR$headers 中。

定制

为了进一步定制 Playground,发布视图

php artisan vendor:publish --tag=graphql-playground-view

您可以使用它进行各种定制。

更改 playground 实例的设置

在发布的视图中调用 GraphQLPlayground.init 时添加额外的设置

GraphQLPlayground.init(document.getElementById('root'), {
  endpoint: "{{ url(config('graphql-playground.endpoint')) }}",
  subscriptionEndpoint: "{{ config('graphql-playground.subscriptionEndpoint') }}",
  // See https://github.com/graphql/graphql-playground#properties for available settings
})

配置会话认证

基于会话的认证可以与 Laravel Sanctum 一起使用。如果您通过会话和 CSRF 使用 GraphQL,请将以下内容添加到发布的视图中的 <head>

<meta name="csrf-token" content="{{ csrf_token() }}">

修改 Playground 配置

GraphQLPlayground.init(document.getElementById('root'), {
  endpoint: "{{ url(config('graphql-playground.endpoint')) }}",
  subscriptionEndpoint: "{{ config('graphql-playground.subscriptionEndpoint') }}",
+ settings: {
+   'request.credentials': 'same-origin',
+   'request.globalHeaders': {
+     'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
+   }
+ }
})

确保您的路由在 config/graphql-playground.php 中包含 web 中间件组

    'route' => [
        'uri' => '/graphql-playground',
        'name' => 'graphql-playground',
+       'middleware' => ['web']
    ]

本地资产

如果您想从您自己的服务器提供资产,可以使用以下命令下载

php artisan graphql-playground:download-assets

这将必要的 CSS、JS 和 Favicon 放入您的 public 目录。如果您已下载资产,它们将替代来自 CDN 的在线版本。

安全

如果您不想在生产环境中启用 GraphQL playground,您可以在配置文件中禁用它。最简单的方法是设置环境变量 GRAPHQL_PLAYGROUND_ENABLED=false

如果您想保护 GraphQL playground 的路由,您可以在配置文件中添加自定义中间件。