Skip to content

Commit

Permalink
Controller request/response
Browse files Browse the repository at this point in the history
  • Loading branch information
chillu committed Sep 17, 2016
1 parent df951de commit a378c0f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
31 changes: 28 additions & 3 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,54 @@

use SilverStripe\Control\Controller as BaseController;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Config\Config;

class Controller extends BaseController
{

/**
* @var Manager
*/
protected $manager;

public function index(HTTPRequest $request) {
$manager = $this->getManager();
$query = $request->getVar('query');
$params = $request->getVar('params');

$schema = $manager->getSchema();
if(is_string($params)) {
$params = json_decode($params, true);
}

$manager = $this->getManager();
$response = $manager->query($query, $params);

return (new HTTPResponse(json_encode($response)))
->addHeader('Content-Type', 'text/json');
}

/**
* @return Manager
*/
protected function getManager() {
public function getManager() {
if($this->manager) {
return $this->manager;
}

// Get a service rather than an instance (to allow procedural configuration)
$config = Config::inst()->get('SilverStripe\GraphQL', 'schema');
$manager = Injector::inst()->create(Manager::class, $config);

return $manager;
}

/**
* @param Manager $manager
*/
public function setManager($manager)
{
$this->manager = $manager;
}

}
13 changes: 13 additions & 0 deletions tests/ControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,28 @@

namespace SilverStripe\Tests\GraphQL;

use SilverStripe\Control\HTTPRequest;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\GraphQL\Manager;
use SilverStripe\GraphQL\Controller;
use SilverStripe\GraphQL\Tests\Fake\TypeCreatorFake;
use SilverStripe\GraphQL\Tests\Fake\QueryCreatorFake;
use SilverStripe\Core\Config\Config;
use ReflectionClass;

class ControllerTest extends SapphireTest
{

public function testIndex()
{
$controller = new Controller();
$manager = new Manager();
$manager->addType(TypeCreatorFake::class, 'mytype');
$manager->addQuery(QueryCreatorFake::class, 'myquery');
$controller->setManager($manager);
$response = $controller->index(new HTTPRequest('GET', ''));
$this->assertFalse($response->isError());
}

public function testGetGetManagerPopulatesFromConfig()
{
Expand Down

0 comments on commit a378c0f

Please sign in to comment.