vahidirn / graphql-upload
支持GraphQL文件上传的中间件
dev-master
2019-04-21 11:02 UTC
Requires
- php: ^7.1
- ext-json: *
- psr/http-server-middleware: ^1.0
- webonyx/graphql-php: ^0.10.2
Requires (Dev)
- friendsofphp/php-cs-fixer: @stable
- phpstan/phpstan: ^0.10.5
- phpunit/phpunit: @stable
- zendframework/zend-diactoros: @stable
This package is not auto-updated.
Last update: 2024-10-01 12:20:28 UTC
README
这是一个支持GraphQL文件上传的PSR-15中间件。它实现了多部分请求规范,用于webonyx/graphql-php。
快速开始
使用composer安装库
composer require vahidirn/graphql-upload
配置为中间件
在Zend Expressive中,通常在config/routes.php
中配置,例如
use Application\Action\GraphQLAction; use Zend\Expressive\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 Zend\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,zend-diactoros是创建PSR-7请求的许多实现之一。