blib/lib/Dancer2/Plugin/GraphQL.pm

filter: Statementstmt 94.2% 65 / 69 Branchbran 83.3% 10 / 12 Conditioncond 63.6% 7 / 11 MC/DCmcdc 20.0% 1 / 5 Subroutinesub 92.3% 12 / 13 Podpod 0.0% 0 / 1 totaltotal 85.5% 95 / 111 CC 12 SCAR 13.2
CC
12
Cov
89%
__ANON__
6.0
__ANON__
6.0
_safe_serialize
3.2
CRAP 3.7
↑ Summary
1 package Dancer2::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 Dancer2::Core::Types qw(Bool);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Dancer2::Plugin;
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 Module::Runtime qw(require_module);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 2 our $VERSION = '0.09';
11  
12 has graphiql => (
13 is => 'ro',
14 isa => Bool,
15 0 ▶ from_config => sub { '' },
Subroutine __ANON__: not called CC=1 SCAR=6.9
16 2 );
17  
18 2 my @DEFAULT_METHODS = qw(get post);
19 2 my $TEMPLATE = join '', <DATA>;
20 2 ▶my $EXECUTE = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
21 2 my ($schema, $query, $root_value, $per_request, $variables, $operationName, $field_resolver) = @_;
22 2 execute(
23 $schema,
24 $query,
25 $root_value,
26 $per_request,
27 $variables,
28 $operationName,
29 $field_resolver,
30 );
31 2 };
32 1 ▶sub make_code_closure {
Subroutine make_code_closure: called CC=1 SCAR=0.0
Pod undocumented
33 1 my ($schema, $root_value, $field_resolver) = @_;
34 1 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
35 1 my ($app, $body, $execute) = @_;
36 $execute->(
37 $schema,
38 $body->{query},
39 $root_value,
40 $app->request->headers,
41 $body->{variables},
42 $body->{operationName},
43 1 $field_resolver,
44 );
45 1 };
46 };
47  
48 2 my $JSON = JSON::MaybeXS->new->utf8->allow_nonref;
49 4 ▶sub _safe_serialize {
Subroutine _safe_serialize: called CC=2 SCAR=11.6
50 4 ▶ my $data = shift or return 'undefined';
Branch: 1 branch
BranchTrueFalseTotal
my $data = shift() or return "undefined" 0 4 4
51 0 my $json = $JSON->encode( $data );
52 0 $json =~ s#/#\\/#g;
53 0 return $json;
54 }
55  
56 # DSL args after $pattern: $schema, $root_value, $resolver, $handler
57 3 ▶plugin_keywords graphql => sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
58 3 my ($plugin, $pattern, @rest) = @_;
59 3 my ($schema, $root_value, $field_resolver, $handler);
60 3 ▶ if (ref $rest[0] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rest[0] eq "ARRAY") 1 2 3
61 1 my ($class, @values) = @{ shift @rest };
62 1 $class = "GraphQL::Plugin::Convert::$class";
63 1 require_module $class;
64 1 my $converted = $class->to_graphql(@values);
65 1 unshift @rest, @{$converted}{qw(schema root_value resolver)};
66 1 ▶ push @rest, make_code_closure(@rest[0..2]) if @rest < 4;
Branch: 1 branch
BranchTrueFalseTotal
if @rest < 4 1 0 1
67 }
68 3 ▶ if (@rest == 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rest == 4) { } 1 2 3
69 1 ($schema, $root_value, $field_resolver, $handler) = @rest;
70 } else {
71 2 ($schema, $root_value) = grep ref ne 'CODE', @rest;
72 2 my @codes = grep ref eq 'CODE', @rest;
73 # if only one, is $handler
74 2 ($handler, $field_resolver) = reverse @codes;
75 2 ▶ $handler ||= make_code_closure($schema, $root_value, $field_resolver);
Condition33%1/3
$handler ||= make_code_closure($schema, $root_value, $field_resolver)
l!l&&r!l&&!r
200
MC/DC0%0/2
$handler ||= make_code_closure($schema, $root_value, $field_resolver)
$handler make_code_closure($schema, $root_value, $field_resolver)
Truth table33%1/3
A ||= B
A= $handlerB= make_code_closure($schema, $root_value, $field_resolver)
ABresult
1X1
011
000
76 }
77 4 ▶ my $ajax_route = sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
78 4 my ($app) = @_;
79 4 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($plugin->graphiql and ($app->request->header("Accept") // "") =~ m[^text/html\b] and not defined $app->request->params->{"raw"}) 1 3 4
Condition75%6/8
$plugin->graphiql and ($app->request->header("Accept") // "") =~ m[^text/html\b] and not defined $app->request->params->{"raw"}
!ll&&!rl&&r
301
$plugin->graphiql and ($app->request->header("Accept") // "") =~ m[^text/html\b]
!ll&&!rl&&r
031
$app->request->header("Accept") // ""
l!l
13
MC/DC33%1/3
$plugin->graphiql and ($app->request->header("Accept") // "") =~ m[^text/html\b] and not defined $app->request->params->{"raw"}
$plugin->graphiql $app->request->header("Accept") not defined $app->request->params->{"raw"}
Truth table50%2/4
A and B and not(C)
A= $plugin->graphiqlB= $app->request->header("Accept")C= not defined $app->request->params->{"raw"}
ABCresult
0XX0
10X0
1100
1111
80 $plugin->graphiql and
81 ($app->request->header('Accept')//'') =~ /^text\/html\b/ and
82 !defined $app->request->params->{raw}
83 ) {
84 # disable layout
85 1 my $layout = $app->config->{layout};
86 1 $app->config->{layout} = undef;
87 my $result = $app->template(\$TEMPLATE, {
88 title => 'GraphiQL',
89 graphiql_version => 'latest',
90 queryString => _safe_serialize( $app->request->params->{query} ),
91 operationName => _safe_serialize( $app->request->params->{operationName} ),
92 resultString => _safe_serialize( $app->request->params->{result} ),
93 1 variablesString => _safe_serialize( $app->request->params->{variables} ),
94 });
95 1 $app->config->{layout} = $layout;
96 1 $app->send_as(html => $result);
97 }
98 3 my $body = $JSON->decode($app->request->body);
99 3 my $data = eval { $handler->($app, $body, $EXECUTE) };
100 3 ▶ $data = { errors => [ { message => $@ } ] } if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 2 3
101 3 $app->send_as(JSON => $data);
102 3 };
103 3 foreach my $method (@DEFAULT_METHODS) {
104 6 $plugin->app->add_route(
105 method => $method,
106 regexp => $pattern,
107 code => $ajax_route,
108 );
109 }
110 2 };
111  
112 =pod
113  
114 =encoding UTF-8
115  
116 =head1 NAME
117  
118 Dancer2::Plugin::GraphQL - a plugin for adding GraphQL route handlers
119  
120 =head1 SYNOPSIS
121  
122 package MyWebApp;
123  
124 use Dancer2;
125 use Dancer2::Plugin::GraphQL;
126 use GraphQL::Schema;
127  
128 my $schema = GraphQL::Schema->from_doc(<<'EOF');
129 schema {
130 query: QueryRoot
131 }
132 type QueryRoot {
133 helloWorld: String
134 }
135 EOF
136 graphql '/graphql' => $schema, { helloWorld => 'Hello, world!' };
137  
138 dance;
139  
140 # OR, equivalently:
141 graphql '/graphql' => $schema => sub {
142 my ($app, $body, $execute) = @_;
143 # returns JSON-able Perl data
144 $execute->(
145 $schema,
146 $body->{query},
147 undef, # $root_value
148 $app->request->headers,
149 $body->{variables},
150 $body->{operationName},
151 undef, # $field_resolver
152 );
153 };
154  
155 # OR, with bespoke user-lookup and caching:
156 graphql '/graphql' => sub {
157 my ($app, $body, $execute) = @_;
158 my $user = MyStuff::User->lookup($app->request->headers->header('X-Token'));
159 die "Invalid user\n" if !$user; # turned into GraphQL { errors => [ ... ] }
160 my $cached_result = MyStuff::RequestCache->lookup($user, $body->{query});
161 return $cached_result if $cached_result;
162 MyStuff::RequestCache->cache_and_return($execute->(
163 $schema,
164 $body->{query},
165 undef, # $root_value
166 $user, # per-request info
167 $body->{variables},
168 $body->{operationName},
169 undef, # $field_resolver
170 ));
171 };
172  
173 =head1 DESCRIPTION
174  
175 The C<graphql> keyword which is exported by this plugin allow you to
176 define a route handler implementing a GraphQL endpoint.
177  
178 Parameters, after the route pattern.
179 The first three can be replaced with a single array-ref. If so,
180 the first element is a classname-part, which will be prepended with
181 "L<GraphQL::Plugin::Convert>::". The other values will be passed to
182 that class's L<GraphQL::Plugin::Convert/to_graphql> method. The returned
183 hash-ref will be used to set options.
184  
185 E.g.
186  
187 graphql '/graphql' => [ 'Test' ]; # uses GraphQL::Plugin::Convert::Test
188  
189 =over 4
190  
191 =item $schema
192  
193 A L<GraphQL::Schema> object.
194  
195 =item $root_value
196  
197 An optional root value, passed to top-level resolvers.
198  
199 =item $field_resolver
200  
201 An optional field resolver, replacing the GraphQL default.
202  
203 =item $route_handler
204  
205 An optional route-handler, replacing the plugin's default - see example
206 above for possibilities.
207  
208 It must return JSON-able Perl data in the GraphQL format, which is a hash
209 with at least one of a C<data> key and/or an C<errors> key.
210  
211 If it throws an exception, that will be turned into a GraphQL-formatted
212 error.
213  
214 =back
215  
216 If you supply two code-refs, they will be the C<$resolver> and
217 C<$handler>. If you only supply one, it will be C<$handler>. To be
218 certain, pass all four post-pattern arguments.
219  
220 The route handler code will be compiled to behave like the following:
221  
222 =over 4
223  
224 =item *
225  
226 Passes to the L<GraphQL> execute, possibly via your supplied handler,
227 the given schema, C<$root_value> and C<$field_resolver>.
228  
229 =item *
230  
231 The action built matches POST / GET requests.
232  
233 =item *
234  
235 Returns GraphQL results in JSON form.
236  
237 =back
238  
239 =head1 CONFIGURATION
240  
241 By default the plugin will not return GraphiQL, but this can be overridden
242 with plugin setting 'graphiql', to true.
243  
244 Here is example to use GraphiQL:
245  
246 plugins:
247 GraphQL:
248 graphiql: true
249  
250 =head1 AUTHOR
251  
252 Ed J
253  
254 Based heavily on L<Dancer2::Plugin::Ajax> by "Dancer Core Developers".
255  
256 =head1 COPYRIGHT AND LICENSE
257  
258 This is free software; you can redistribute it and/or modify it under
259 the same terms as the Perl 5 programming language system itself.
260  
261 =cut
262  
263 2 1;
264  
265 __DATA__
↑ Summary