hkreuter / graphql-upload
一个支持GraphQL文件上传的中间件。从ecodev/graphql-upload分支而来。
6.1.0
2020-12-02 23:44 UTC
Requires
- php: ^7.2 || ^8.0
- ext-json: *
- psr/http-server-middleware: ^1.0
- webonyx/graphql-php: ^14.3
Requires (Dev)
- friendsofphp/php-cs-fixer: @stable
- laminas/laminas-diactoros: @stable
- phpstan/phpstan: @stable
- phpunit/phpunit: @stable
This package is auto-updated.
Last update: 2024-09-29 06:14:31 UTC
README
一个支持GraphQL文件上传的PSR-15中间件。它实现了multipart请求规范,用于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', ]), '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请求的许多实现之一。