ecodev/graphql-upload

支持 GraphQL 文件上传的中间件

7.0.0 2023-01-12 03:19 UTC

README

Build Status Code Quality Code Coverage Total Downloads Latest Stable Version License Join the chat at https://gitter.im/Ecodev/graphql-upload

一个支持 GraphQL 文件上传的 PSR-15 中间件。它实现了 多部分请求规范,用于 webonyx/graphql-php

快速开始

使用 Composer 安装库

composer require ecodev/graphql-upload

配置为中间件

在 Laminas Mezzio 中,通常在 config/routes.php 中配置如下

use Application\Action\GraphQLAction;
use Mezzio\Helper\BodyParams\BodyParamsMiddleware;
use GraphQL\Upload\UploadMiddleware;

$app->post('/graphql', [
    BodyParamsMiddleware::class, 
    UploadMiddleware::class, // This is the magic
    GraphQLAction::class,
], 'graphql');

其他框架

此库是 PSR-15 的实现,因此可以与任何支持 PSR-15 的框架一起使用。有关特定配置说明,请参阅您的框架文档。

如果您的框架不支持 PSR-15 中间件,您可能需要某种类型的桥梁。同样,请参阅您的框架以获取特定说明。或者,您可以使用下面的直接使用方法进行手动集成。

直接使用

如果您不使用中间件,可以直接调用,如下所示

<?php

use GraphQL\Server\StandardServer;
use GraphQL\Upload\UploadMiddleware;
use Laminas\Diactoros\ServerRequestFactory;

// Create request (or get it from a framework)
$request = ServerRequestFactory::fromGlobals();
$request = $request->withParsedBody(json_decode($request->getBody()->getContents(), true));

// Process uploaded files
$uploadMiddleware = new UploadMiddleware();
$request = $uploadMiddleware->processRequest($request);

// Execute request and emits response
$server = new StandardServer(/* your config here */);
$result = $server->executePsrRequest($request);
$server->getHelper()->sendResponse($result);

在模式中使用

然后您可以在您的突变中使用它,如下所示

<?php

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use GraphQL\Upload\UploadType;
use Psr\Http\Message\UploadedFileInterface;

// Build your Schema
$schema = new Schema([
    'query' => new ObjectType([
        'name' => 'Query',
        'fields' => [],
    ]),
    'mutation' => new ObjectType([
        'name' => 'Mutation',
        'fields' => [
            'testUpload' => [
                'type' => Type::string(),
                'args' => [
                    'text' => Type::string(),
                    'file' => new UploadType(),
                ],
                'resolve' => function ($root, array $args): string {
                    /** @var UploadedFileInterface $file */
                    $file = $args['file'];

                    // Do something with the file
                    $file->moveTo('some/folder/in/my/project');

                    return 'Uploaded file was ' . $file->getClientFilename() . ' (' . $file->getClientMediaType() . ') with description: ' . $args['text'];
                },
            ],
        ],
    ]),
]);

限制

  • 它仅与 PSR-7 请求一起工作。如果您尚未使用 PSR-7,laminas-diactoros 是许多实现之一,可用于创建 PSR-7 请求。