blib/lib/Mojolicious/Plugin/GraphQL.pm

filter: Statementstmt 96.9% 161 / 166 Branchbran 77.7% 42 / 54 Conditioncond 73.3% 11 / 15 MC/DCmcdc 37.5% 3 / 8 Subroutinesub 97.4% 38 / 39 Podpod 50.0% 1 / 2 totaltotal 90.1% 256 / 284 CC 34 SCAR 13.4
CC
34
Cov
91%
__ANON__
10.2
register
8.0
__ANON__
6.1
CRAP 3.8
↑ Summary
1 package Mojolicious::Plugin::GraphQL;
2 # ABSTRACT: a plugin for adding GraphQL route handlers
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Mojo::JSON qw(decode_json to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use GraphQL::Execution qw(execute);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use GraphQL::Type::Library -all;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use GraphQL::Debug qw(_debug);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use Module::Runtime qw(require_module);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use curry;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 2 our $VERSION = '0.19';
16 2 our @EXPORT_OK = qw(promise_code);
17  
18 2 ▶use constant DEBUG => $ENV{GRAPHQL_DEBUG};
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use constant promise_code => +{
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶ all => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
21 # current Mojo::Promise->all only works on promises, force that
22 1 ▶ my @promises = map is_Promise($_)
Branch: 1 branch
BranchTrueFalseTotal
is_Promise($_) ? : 1 0 1
23 ? $_ : Mojo::Promise->new->resolve($_),
24 @_;
25 # only actually works when first promise-instance is a
26 # Mojo::Promise, so force it to be one. hoping will be fixed soon
27 1 Mojo::Promise->all(@promises);
28 },
29 2 resolve => Mojo::Promise->curry::resolve,
30 reject => Mojo::Promise->curry::reject,
31 new => Mojo::Promise->curry::new,
32 2 };
33 # from https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/message-types.ts
34 2 ▶use constant ws_protocol => +{
Subroutine BEGIN: called CC=1 SCAR=0.0
35 # no legacy ones like 'init'
36 GQL_CONNECTION_INIT => 'connection_init', # Client -> Server
37 GQL_CONNECTION_ACK => 'connection_ack', # Server -> Client
38 GQL_CONNECTION_ERROR => 'connection_error', # Server -> Client
39 # NOTE: The keep alive message type does not follow the standard due to connection optimizations
40 GQL_CONNECTION_KEEP_ALIVE => 'ka', # Server -> Client
41 GQL_CONNECTION_TERMINATE => 'connection_terminate', # Client -> Server
42 GQL_START => 'start', # Client -> Server
43 GQL_DATA => 'data', # Server -> Client
44 GQL_ERROR => 'error', # Server -> Client
45 GQL_COMPLETE => 'complete', # Server -> Client
46 GQL_STOP => 'stop', # Client -> Server
47 2 };
48  
49 2 my @DEFAULT_METHODS = qw(get post);
50 2 ▶use constant EXECUTE => sub { $_[7] = promise_code(); goto &execute; };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
51 2 ▶use constant SUBSCRIBE => sub {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
52 3 splice @_, 7, 1, promise_code();
53 3 goto &GraphQL::Subscription::subscribe;
54 2 };
55 4 ▶sub make_code_closure {
Subroutine make_code_closure: called CC=1 SCAR=0.0
Pod undocumented
56 4 my ($schema, $root_value, $field_resolver) = @_;
57 5 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
58 5 my ($c, $body, $execute, $subscribe_resolver) = @_;
59 $execute->(
60 $schema,
61 $body->{query},
62 $root_value,
63 $c->req->headers,
64 $body->{variables},
65 $body->{operationName},
66 5 ▶ $field_resolver,
Branch: 1 branch
BranchTrueFalseTotal
$subscribe_resolver ? : 3 2 5
67 $subscribe_resolver ? (undef, $subscribe_resolver) : (),
68 );
69 4 };
70 }
71  
72 12 ▶sub _safe_serialize {
Subroutine _safe_serialize: called CC=2 SCAR=6.9
73 12 ▶ my $data = shift // return 'undefined';
Condition100%2/2
shift() // (return "undefined")
l!l
111
MC/DC100%1/1
shift() // (return "undefined")
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
74 1 my $json = to_json($data);
75 1 $json =~ s#/#\\/#g;
76 1 return $json;
77 }
78  
79 2 ▶sub _graphiql_wrap {
Subroutine _graphiql_wrap: called CC=1 SCAR=0.0
80 2 my ($wrappee, $use_subscription) = @_;
81 4 ▶ sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
82 4 my ($c) = @_;
83 4 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (($c->req->headers->header("Accept") // "") =~ m[^text/html\b]u and not defined $c->req->query_params->param("raw")) 3 1 4
Condition80%4/5
($c->req->headers->header("Accept") // "") =~ m[^text/html\b]u and not defined $c->req->query_params->param("raw")
!ll&&!rl&&r
103
$c->req->headers->header("Accept") // ""
l!l
31
MC/DC50%1/2
($c->req->headers->header("Accept") // "") =~ m[^text/html\b]u and not defined $c->req->query_params->param("raw")
$c->req->headers->header("Accept") not defined $c->req->query_params->param("raw")
Truth table66%2/3
A and not(B)
A= $c->req->headers->header("Accept")B= not defined $c->req->query_params->param("raw")
ABresult
0X0
100
111
84 # not as ignores Firefox-sent multi-accept: $c->accepts('', 'html') and
85 ($c->req->headers->header('Accept')//'') =~ /^text\/html\b/ and
86 !defined $c->req->query_params->param('raw')
87 ) {
88 3 my $p = $c->req->query_params;
89 3 my $https = $c->req->is_secure;
90 3 ▶ return $c->render(
Branch: 2 branches
BranchTrueFalseTotal
$use_subscription ? : 1 2 3
$https ? : 0 1 1
91 template => 'graphiql',
92 layout => undef,
93 title => 'GraphiQL',
94 graphiql_version => 'latest',
95 queryString => _safe_serialize( $p->param('query') ),
96 operationName => _safe_serialize( $p->param('operationName') ),
97 resultString => _safe_serialize( $p->param('result') ),
98 variablesString => _safe_serialize( $p->param('variables') ),
99 subscriptionEndpoint => to_json(
100 # if serialises to true (which empty-string will), turns on subs code
101 $use_subscription
102 ? $c->url_for->to_abs->scheme($https ? 'wss' : 'ws')
103 : 0
104 ),
105 );
106 }
107 1 goto $wrappee;
108 2 };
109 }
110  
111 12 ▶sub _decode {
Subroutine _decode: called CC=2 SCAR=6.9
112 12 my ($bytes) = @_;
113 12 my $body = eval { decode_json($bytes) };
114 # conceal error info like versions from attackers
115 12 ▶ return (0, { errors => [ { message => "Malformed request" } ] }) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 11 12
116 11 (1, $body);
117 }
118  
119 7 ▶sub _execute {
Subroutine _execute: called CC=2 SCAR=6.9
120 7 my ($c, $body, $handler, $execute, $subscribe_fn) = @_;
121 7 my $data = eval { $handler->($c, $body, $execute, $subscribe_fn) };
122 7 ▶ return { errors => [ { message => $@ } ] } if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 6 7
123 6 $data;
124 }
125  
126 6 ▶sub _make_route_handler {
Subroutine _make_route_handler: called CC=1 SCAR=0.0
127 6 my ($handler) = @_;
128 5 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
129 5 my ($c) = @_;
130 5 my ($decode_ok, $body) = _decode($c->req->body);
131 5 ▶ return $c->render(json => $body) if !$decode_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $decode_ok 1 4 5
132 4 my $data = _execute($c, $body, $handler, EXECUTE());
133 4 ▶ return $c->render(json => $data) if !is_Promise($data);
Branch: 1 branch
BranchTrueFalseTotal
unless is_Promise($data) 3 1 4
134 1 ▶ $data->then(sub { $c->render(json => shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
135 6 };
136 }
137  
138 3 ▶sub _make_connection_handler {
Subroutine _make_connection_handler: called CC=1 SCAR=0.1
139 3 my ($handler, $subscribe_resolver, $context) = @_;
140 7 ▶ sub {
Subroutine __ANON__: called CC=9 SCAR=23.2
141 7 my ($c, $bytes) = @_;
142 7 my ($decode_ok, $body) = _decode($bytes);
143 return $c->send({json => {
144 payload => $body,
145 type => ($context->{connected}
146 7 ▶ ? ws_protocol->{GQL_ERROR} : ws_protocol->{GQL_CONNECTION_ERROR}),
Branch: 2 branches
BranchTrueFalseTotal
unless $decode_ok 0 7 7
$context->{'connected'} ? : 0 0 0
147 }}) if !$decode_ok;
148 7 my $msg_type = $body->{type};
149 7 ▶ if ($msg_type eq ws_protocol->{GQL_CONNECTION_INIT}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($msg_type eq {GQL_COMPLETE => 'complete', GQL_CONNECTION_ACK => 'connection_ack', GQL_CONNECTION_ERROR => 'connection_error', GQL_CONNECTION_INIT => 'connection_init', GQL_CONNECTION_KEEP_ALIVE => 'ka', GQL_CONNECTION_TERMINATE => 'connection_terminate', GQL_DATA => 'data', GQL_ERROR => 'error', GQL_START => 'start', GQL_STOP => 'stop'}->{'GQL_CONNECTION_INIT'}) { } 3 4 7
elsif ($msg_type eq {GQL_COMPLETE => 'complete', GQL_CONNECTION_ACK => 'connection_ack', GQL_CONNECTION_ERROR => 'connection_error', GQL_CONNECTION_INIT => 'connection_init', GQL_CONNECTION_KEEP_ALIVE => 'ka', GQL_CONNECTION_TERMINATE => 'connection_terminate', GQL_DATA => 'data', GQL_ERROR => 'error', GQL_START => 'start', GQL_STOP => 'stop'}->{'GQL_START'}) { } 3 1 4
elsif ($msg_type eq {GQL_COMPLETE => 'complete', GQL_CONNECTION_ACK => 'connection_ack', GQL_CONNECTION_ERROR => 'connection_error', GQL_CONNECTION_INIT => 'connection_init', GQL_CONNECTION_KEEP_ALIVE => 'ka', GQL_CONNECTION_TERMINATE => 'connection_terminate', GQL_DATA => 'data', GQL_ERROR => 'error', GQL_START => 'start', GQL_STOP => 'stop'}->{'GQL_STOP'}) { } 1 0 1
150 3 $context->{connected} = 1;
151 $c->send({json => {
152 type => ws_protocol->{GQL_CONNECTION_ACK}
153 3 }});
154 3 ▶ if ($context->{keepalive}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($context->{"keepalive"}) 1 2 3
155 1 my $cb;
156 2 ▶ $cb = sub {
Subroutine __ANON__: called CC=3 SCAR=12.5
157 2 ▶ return unless $c->tx and $context->{keepalive};
Branch: 1 branch
BranchTrueFalseTotal
unless $c->tx and $context->{"keepalive"} 0 2 2
Condition33%1/3
$c->tx and $context->{"keepalive"}
!ll&&!rl&&r
002
MC/DC0%0/2
$c->tx and $context->{"keepalive"}
$c->tx $context->{"keepalive"}
Truth table33%1/3
A and B
A= $c->txB= $context->{"keepalive"}
ABresult
0X0
100
111
158 $c->send({json => {
159 type => ws_protocol->{GQL_CONNECTION_KEEP_ALIVE},
160 2 }});
161 2 Mojo::IOLoop->timer($context->{keepalive} => $cb);
162 1 };
163 1 $cb->();
164 }
165 3 return;
166 } elsif ($msg_type eq ws_protocol->{GQL_START}) {
167 3 $context->{id} = $body->{id};
168 my $data = _execute(
169 3 $c, $body->{payload}, $handler, SUBSCRIBE(), $subscribe_resolver,
170 );
171 return $c->send({json => {
172 payload => $data, type => ws_protocol->{GQL_ERROR},
173 3 ▶ }}) if !is_Promise($data);
Branch: 1 branch
BranchTrueFalseTotal
unless is_Promise($data) 0 3 3
174 $data->then(
175 3 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
176 3 my ($result) = @_;
177 3 ▶ if (!is_AsyncIterator($result)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (is_AsyncIterator($result)) 0 3 3
178 # subscription error
179 $c->send({json => {
180 payload => $result, type => ws_protocol->{GQL_ERROR},
181 id => $context->{id},
182 0 }});
183 0 $c->finish;
184 0 return;
185 }
186 3 my $promise;
187 5 ▶ $context->{async_iterator} = $result->map_then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
188 5 DEBUG and _debug('MLPlugin.ai_cb', $context, @_);
189 $c->send({json => {
190 payload => $_[0],
191 type => ws_protocol->{GQL_DATA},
192 id => $context->{id},
193 5 }});
194 5 $promise = $context->{async_iterator}->next_p;
195 $c->send({json => {
196 type => ws_protocol->{GQL_COMPLETE},
197 id => $context->{id},
198 5 ▶ }}) if !$promise; # exhausted, tell client
Branch: 1 branch
BranchTrueFalseTotal
if not $promise 1 4 5
199 3 });
200 3 $promise = $context->{async_iterator}->next_p; # start the process
201 },
202 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
203 $c->send({json => {
204 payload => $_[0], type => ws_protocol->{GQL_ERROR},
205 id => $context->{id},
206 0 }});
207 0 $c->finish;
208 },
209 3 );
210 } elsif ($msg_type eq ws_protocol->{GQL_STOP}) {
211 $c->send({json => {
212 type => ws_protocol->{GQL_COMPLETE},
213 id => $context->{id},
214 1 }});
215 1 ▶ $context->{async_iterator}->close_tap if $context->{async_iterator};
Branch: 1 branch
BranchTrueFalseTotal
if $context->{"async_iterator"} 1 0 1
216 1 undef %$context; # relinquish our refcounts
217 }
218 }
219 3 }
220  
221 2 ▶sub _make_subs_route_handler {
Subroutine _make_subs_route_handler: called CC=1 SCAR=0.0
222 2 my ($handler, $subscribe_resolver, $keepalive) = @_;
223 2 require GraphQL::Subscription;
224 3 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
225 3 my ($c) = @_;
226 # without this, GraphiQL won't accept is valid
227 3 my $sec_websocket_protocol = $c->tx->req->headers->sec_websocket_protocol;
228 3 ▶ $c->tx->res->headers->sec_websocket_protocol($sec_websocket_protocol)
Branch: 1 branch
BranchTrueFalseTotal
if $sec_websocket_protocol 0 3 3
229 if $sec_websocket_protocol;
230 3 my %context = (keepalive => $keepalive);
231 3 $c->on(text => _make_connection_handler($handler, $subscribe_resolver, \%context));
232 3 ▶ $c->on(finish => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
233 3 ▶ $context{async_iterator}->close_tap if $context{async_iterator};
Branch: 1 branch
BranchTrueFalseTotal
if $context{"async_iterator"} 2 1 3
234 3 undef %context; # relinquish our refcounts
235 3 });
236 2 };
237 }
238  
239 6 ▶sub register {
Subroutine register: called CC=8 SCAR=20.8
Pod documented
240 6 my ($self, $app, $conf) = @_;
241 6 ▶ if ($conf->{convert}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conf->{"convert"}) 3 3 6
242 3 my ($class, @values) = @{ $conf->{convert} };
243 3 $class = "GraphQL::Plugin::Convert::$class";
244 3 require_module $class;
245 3 my $converted = $class->to_graphql(@values);
246 3 $conf = { %$conf, %$converted };
247 }
248 6 ▶ die "Need schema\n" if !$conf->{schema};
Branch: 1 branch
BranchTrueFalseTotal
unless $conf->{"schema"} 0 6 6
249 6 ▶ my $endpoint = $conf->{endpoint} || '/graphql';
Condition100%2/2
$conf->{'endpoint'} || '/graphql'
l!l
51
MC/DC100%1/1
$conf->{'endpoint'} || '/graphql'
$conf->{'endpoint'}
Truth table100%2/2
A
A= $conf->{'endpoint'}
Aresult
11
00
250 my $handler = $conf->{handler} || make_code_closure(
251 6 ▶ @{$conf}{qw(schema root_value resolver)}
Condition66%2/3
$conf->{'handler'} || make_code_closure(@{$conf;}{'schema', 'root_value', 'resolver'})
l!l&&r!l&&!r
240
MC/DC0%0/2
$conf->{'handler'} || make_code_closure(@{$conf;}{'schema', 'root_value', 'resolver'})
$conf->{'handler'} make_code_closure(@{$conf;}{'schema', 'root_value', 'resolver'})
Truth table66%2/3
A || B
A= $conf->{'handler'}B= make_code_closure(@{$conf;}{'schema', 'root_value', 'resolver'})
ABresult
1X1
011
000
252 );
253 1 push @{$app->renderer->classes}, __PACKAGE__
254 6 ▶ unless grep $_ eq __PACKAGE__, @{$app->renderer->classes};
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($_ eq __PACKAGE__), @{$app->renderer->classes;}) 1 5 6
255 6 my $route_handler = _make_route_handler($handler);
256 $route_handler = _graphiql_wrap($route_handler, $conf->{schema}->subscription)
257 6 ▶ if $conf->{graphiql};
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"graphiql"} 2 4 6
258 6 my $r = $app->routes;
259 6 ▶ if ($conf->{schema}->subscription) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conf->{"schema"}->subscription) 2 4 6
260 # must add "websocket" route before "any" because checked in define order
261 my $subs_route_handler = _make_subs_route_handler(
262 2 $handler, @{$conf}{qw(subscribe_resolver keepalive)},
263 );
264 2 $r->websocket($endpoint => $subs_route_handler);
265 }
266 6 $r->any(\@DEFAULT_METHODS => $endpoint => $route_handler);
267 }
268  
269 2 1;
270  
271 =encoding utf8
272  
273 =head1 NAME
274  
275 Mojolicious::Plugin::GraphQL - a plugin for adding GraphQL route handlers
276  
277 =head1 SYNOPSIS
278  
279 my $schema = GraphQL::Schema->from_doc(<<'EOF');
280 schema {
281 query: QueryRoot
282 }
283 type QueryRoot {
284 helloWorld: String
285 }
286 EOF
287  
288 # for Mojolicious substitute "plugin" with $app->plugin(...
289 # Mojolicious::Lite (with endpoint under "/graphql")
290 plugin GraphQL => {
291 schema => $schema, root_value => { helloWorld => 'Hello, world!' }
292 };
293  
294 # OR, equivalently:
295 plugin GraphQL => {schema => $schema, handler => sub {
296 my ($c, $body, $execute, $subscribe_fn) = @_;
297 # returns JSON-able Perl data
298 $execute->(
299 $schema,
300 $body->{query},
301 { helloWorld => 'Hello, world!' }, # $root_value
302 $c->req->headers,
303 $body->{variables},
304 $body->{operationName},
305 undef, # $field_resolver
306 $subscribe_fn ? (undef, $subscribe_fn) : (), # only passed for subs
307 );
308 }};
309  
310 # OR, with bespoke user-lookup and caching:
311 plugin GraphQL => {schema => $schema, handler => sub {
312 my ($c, $body, $execute, $subscribe_fn) = @_;
313 my $user = MyStuff::User->lookup($app->request->headers->header('X-Token'));
314 die "Invalid user\n" if !$user; # turned into GraphQL { errors => [ ... ] }
315 my $cached_result = MyStuff::RequestCache->lookup($user, $body->{query});
316 return $cached_result if $cached_result;
317 MyStuff::RequestCache->cache_and_return($execute->(
318 $schema,
319 $body->{query},
320 undef, # $root_value
321 $user, # per-request info
322 $body->{variables},
323 $body->{operationName},
324 undef, # $field_resolver
325 $subscribe_fn ? (undef, $subscribe_fn) : (), # only passed for subs
326 ));
327 };
328  
329 # With GraphiQL, on /graphql
330 plugin GraphQL => {schema => $schema, graphiql => 1};
331  
332 =head1 DESCRIPTION
333  
334 This plugin allows you to easily define a route handler implementing a
335 GraphQL endpoint, including a websocket for subscriptions following
336 Apollo's C<subscriptions-transport-ws> protocol.
337  
338 As of version 0.09, it will supply the necessary C<promise_code>
339 parameter to L<GraphQL::Execution/execute>. This means your resolvers
340 can (and indeed should) return Promise objects to function
341 asynchronously. As of 0.15 these must be "Promises/A+" as subscriptions
342 require C<resolve> and C<reject> methods.
343  
344 The route handler code will be compiled to behave like the following:
345  
346 =over 4
347  
348 =item *
349  
350 Passes to the L<GraphQL> execute, possibly via your supplied handler,
351 the given schema, C<$root_value> and C<$field_resolver>. Note as above
352 that the wrapper used in this plugin will supply the hash-ref matching
353 L<GraphQL::Type::Library/PromiseCode>.
354  
355 =item *
356  
357 The action built matches POST / GET requests.
358  
359 =item *
360  
361 Returns GraphQL results in JSON form.
362  
363 =back
364  
365 =head1 OPTIONS
366  
367 L<Mojolicious::Plugin::GraphQL> supports the following options.
368  
369 =head2 convert
370  
371 Array-ref. First element is a classname-part, which will be prepended with
372 "L<GraphQL::Plugin::Convert>::". The other values will be passed
373 to that class's L<GraphQL::Plugin::Convert/to_graphql> method. The
374 returned hash-ref will be used to set options, particularly C<schema>,
375 and probably at least one of C<resolver> and C<root_value>.
376  
377 =head2 endpoint
378  
379 String. Defaults to C</graphql>.
380  
381 =head2 schema
382  
383 A L<GraphQL::Schema> object. As of 0.15, must be supplied.
384  
385 =head2 root_value
386  
387 An optional root value, passed to top-level resolvers.
388  
389 =head2 resolver
390  
391 An optional field resolver, replacing the GraphQL default.
392  
393 =head2 handler
394  
395 An optional route-handler, replacing the plugin's default - see example
396 above for possibilities.
397  
398 It must return JSON-able Perl data in the GraphQL format, which is a hash
399 with at least one of a C<data> key and/or an C<errors> key.
400  
401 If it throws an exception, that will be turned into a GraphQL-formatted
402 error.
403  
404 If being used for a subscription, it will be called with a fourth
405 parameter as shown above. It is safe to not handle this if you are
406 content with GraphQL's defaults.
407  
408 =head2 graphiql
409  
410 Boolean controlling whether requesting the endpoint with C<Accept:
411 text/html> will return the GraphiQL user interface. Defaults to false.
412  
413 # Mojolicious::Lite
414 plugin GraphQL => {schema => $schema, graphiql => 1};
415  
416 =head2 keepalive
417  
418 Defaults to 0, which means do not send. Otherwise will send a keep-alive
419 packet over websocket every specified number of seconds.
420  
421 =head1 METHODS
422  
423 L<Mojolicious::Plugin::GraphQL> inherits all methods from
424 L<Mojolicious::Plugin> and implements the following new ones.
425  
426 =head2 register
427  
428 my $route = $plugin->register(Mojolicious->new, {schema => $schema});
429  
430 Register renderer in L<Mojolicious> application.
431  
432 =head1 EXPORTS
433  
434 Exportable is the function C<promise_code>, which returns a hash-ref
435 suitable for passing as the 8th argument to L<GraphQL::Execution/execute>.
436  
437 =head1 SUBSCRIPTIONS
438  
439 To use subscriptions within your web app, just insert this JavaScript:
440  
441 <script src="//unpkg.com/subscriptions-transport-ws@0.9.16/browser/client.js"></script>
442 # ...
443 const subscriptionsClient = new window.SubscriptionsTransportWs.SubscriptionClient(websocket_uri, {
444 reconnect: true
445 });
446 subscriptionsClient.request({
447 query: "subscription s($c: [String!]) {subscribe(channels: $c) {channel username dateTime message}}",
448 variables: { c: channel },
449 }).subscribe({
450 next(payload) {
451 var msg = payload.data.subscribe;
452 console.log(msg.username + ' said', msg.message);
453 },
454 error: console.error,
455 });
456  
457 Note the use of parameterised queries, where you only need to change
458 the C<variables> parameter. The above is adapted from the sample app,
459 L<https://github.com/graphql-perl/sample-mojolicious>.
460  
461 =head1 SEE ALSO
462  
463 L<GraphQL>
464  
465 L<GraphQL::Plugin::Convert>
466  
467 L<https://github.com/apollographql/subscriptions-transport-ws#client-browser>
468 - Apollo documentation
469  
470 =head1 AUTHOR
471  
472 Ed J
473  
474 Based heavily on L<Mojolicious::Plugin::PODRenderer>.
475  
476 =head1 COPYRIGHT AND LICENSE
477  
478 This is free software; you can redistribute it and/or modify it under
479 the same terms as the Perl 5 programming language system itself.
480  
481 =cut
482  
483 2 1;
484  
485 __DATA__
↑ Summary