Server: Extracted method for emitting response

This commit is contained in:
Vladimir Razuvaev 2017-08-20 02:32:50 +07:00
parent 8098b2b886
commit 71343f2f62
2 changed files with 32 additions and 1 deletions

View File

@ -401,8 +401,17 @@ class Helper
private function doSendResponse($result, $exitWhenDone) private function doSendResponse($result, $exitWhenDone)
{ {
$httpStatus = $this->resolveHttpStatus($result); $httpStatus = $this->resolveHttpStatus($result);
$body = json_encode($result); $this->emitResponse($result, $httpStatus, $exitWhenDone);
}
/**
* @param array|\JsonSerializable $jsonSerializable
* @param int $httpStatus
* @param bool $exitWhenDone
*/
public function emitResponse($jsonSerializable, $httpStatus, $exitWhenDone)
{
$body = json_encode($jsonSerializable);
header('Content-Type: application/json', true, $httpStatus); header('Content-Type: application/json', true, $httpStatus);
echo $body; echo $body;

View File

@ -1,6 +1,7 @@
<?php <?php
namespace GraphQL\Server; namespace GraphQL\Server;
use GraphQL\Error\FormattedError;
use GraphQL\Error\InvariantViolation; use GraphQL\Error\InvariantViolation;
use GraphQL\Executor\ExecutionResult; use GraphQL\Executor\ExecutionResult;
use GraphQL\Executor\Promise\Promise; use GraphQL\Executor\Promise\Promise;
@ -43,6 +44,27 @@ class StandardServer
*/ */
private $helper; private $helper;
/**
* Converts and exception to error and sends spec-compliant HTTP 500 error.
* Useful when an exception is thrown somewhere outside of server execution context
* (e.g. during schema instantiation).
*
* @api
* @param \Throwable $error
* @param bool $debug
* @param bool $exitWhenDone
*/
public static function send500Error($error, $debug = false, $exitWhenDone = false)
{
$response = [
'errors' => [
FormattedError::createFromException($error, $debug)
]
];
$helper = new Helper();
$helper->emitResponse($response, 500, $exitWhenDone);
}
/** /**
* Creates new instance of a standard GraphQL HTTP server * Creates new instance of a standard GraphQL HTTP server
* *