cebugle/laravel-graphql-playground

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

v1.0.0 2023-02-19 10:25 UTC

This package is auto-updated.

Last update: 2024-09-24 08:51:40 UTC


README

已弃用

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

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

GitHub license Packagist Packagist

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

安装

composer require cebugle/laravel-graphql-playground

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

$app->register(Cebugle\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 的路由,可以在配置文件中添加自定义中间件。