-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathwith-dataloader.php
53 lines (46 loc) · 1.47 KB
/
with-dataloader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
use GraphQL\GraphQL;
use GraphQL\Tests\StarWarsData;
use Overblog\DataLoader\DataLoader;
use Overblog\PromiseAdapter\Adapter\ReactPromiseAdapter;
use React\Promise\Promise;
require __DIR__.'/../vendor/autoload.php';
$calls = 0;
$callsIds = [];
$promiseAdapter = new ReactPromiseAdapter();
$batchLoadFn = function ($ids) use (&$calls, &$callsIds, $promiseAdapter) {
$callsIds[] = $ids;
++$calls;
$allCharacters = StarWarsData::humans() + StarWarsData::droids();
$characters = array_intersect_key($allCharacters, array_flip($ids));
return $promiseAdapter->createAll(array_values($characters));
};
$dataLoader = new DataLoader($batchLoadFn, $promiseAdapter);
$schema = createSchema(
function ($character) use ($dataLoader) {
$onFullFilled = function ($value) use ($dataLoader) {
return $dataLoader->loadMany($value['friends']);
};
if ($character instanceof Promise) {
return $character->then($onFullFilled);
} else {
return $onFullFilled($character);
}
},
function ($root, $args) use ($dataLoader) {
return $dataLoader->load($args['id']);
}
);
echo "With DataLoader (using reactPHP promise):\n\n";
executeQueries(
$schema,
$calls,
$callsIds,
new \GraphQL\Executor\Promise\Adapter\ReactPromiseAdapter(),
function () use ($dataLoader) {
$dataLoader->clearAll();
},
function ($promise) {
return DataLoader::await($promise);
}
);