File: Library.pm

package info (click to toggle)
libgraphql-perl 0.54-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 712 kB
  • sloc: perl: 5,094; makefile: 2
file content (461 lines) | stat: -rw-r--r-- 9,935 bytes parent folder | download
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package GraphQL::Type::Library;

use 5.014;
use strict;
use warnings;
use Type::Library
  -base,
  -declare => qw(
    StrNameValid FieldMapInput ValuesMatchTypes DocumentLocation JSONable
    ErrorResult FieldsGot
  );
use Type::Utils -all;
use Types::TypeTiny -all;
use Types::Standard -all;
use JSON::MaybeXS;

our $VERSION = '0.02';
my $JSON = JSON::MaybeXS->new->allow_nonref;

=head1 NAME

GraphQL::Type::Library - GraphQL type library

=head1 SYNOPSIS

    use GraphQL::Type::Library -all;
    has name => (is => 'ro', isa => StrNameValid, required => 1);

=head1 DESCRIPTION

Provides L<Type::Tiny> types.

=head1 TYPES

=head2 StrNameValid

If called with a string that is not a valid GraphQL name, will throw
an exception. Suitable for passing to an C<isa> constraint in L<Moo>.

=cut

declare "StrNameValid", as StrMatch[ qr/^[_a-zA-Z][_a-zA-Z0-9]*$/ ];

=head2 ValuesMatchTypes

Subtype of L<Types::Standard/HashRef>, whose values are hash-refs. Takes
two parameters:

=over

=item value keyname

Optional within the second-level hashes.

=item type keyname

Values will be a L<GraphQL::Type>. Mandatory within the second-level hashes.

=back

In the second-level hashes, the values (if given) must pass the GraphQL
type constraint.

=cut

declare "ValuesMatchTypes",
  constraint_generator => sub {
    my ($value_key, $type_key) = @_;
    declare as HashRef[Dict[
      $type_key => ConsumerOf['GraphQL::Role::Input'],
      slurpy Any,
    ]], where {
      !grep {
        $_->{$value_key} and !$_->{$type_key}->is_valid($_->{$value_key})
      } values %$_
    }, inline_as {
      (undef, <<EOF);
        !grep {
          \$_->{$value_key} and !\$_->{$type_key}->is_valid(\$_->{$value_key})
        } values %{$_[1]}
EOF
    };
};

=head2 FieldsGot

Data item describing the fields found in a particular object in a query.
Preserves their order.

=cut

declare "FieldsGot", as Tuple[ArrayRef[StrNameValid], Map[
  StrNameValid,
  ArrayRef[HashRef]
]];

=head2 FieldMapInput

Hash-ref mapping field names to a hash-ref
description. Description keys, all optional except C<type>:

=over

=item type

GraphQL input type for the field.

=item default_value

Default value for this argument if none supplied. Must be same type as
the C<type> (implemented with type L</ValuesMatchTypes>.
B<NB> this is a Perl value, not a JSON/GraphQL value.

=item description

Description.

=back

=cut

declare "FieldMapInput", as Map[
  StrNameValid,
  Dict[
    type => ConsumerOf['GraphQL::Role::Input'],
    default_value => Optional[Any],
    directives => Optional[ArrayRef[HashRef]],
    description => Optional[Str],
  ]
] & ValuesMatchTypes['default_value', 'type' ];

=head2 FieldMapOutput

Hash-ref mapping field names to a hash-ref
description. Description keys, all optional except C<type>:

=head3 type

GraphQL output type for the field.

=head3 args

A L</FieldMapInput>.

=head3 subscribe

Code-ref to return a subscription to the field from a given
source-object. See L<GraphQL::Subscription/subscribe>.

=head3 deprecation_reason

Reason if deprecated. If given, also sets a boolean key of
C<is_deprecated> to true.

=head3 description

Description.

=head3 resolve

Code-ref to return a given property from a given source-object.
A key concept is to remember that the "object" on which these fields
exist, were themselves returned by other fields.

There are no restrictions on what you can return, so long as it is a
scalar, and if your return type is a L<list|GraphQL::Type::List>, that
scalar is an array-ref.

Emphasis has been put on there being Perl values here. Conversion
between Perl and GraphQL values is taken care of by
L<scalar|GraphQL::Type::Scalar> types, and it is only scalar information
that will be returned to the client, albeit in the shape dictated by
the object types.

An example function that takes a name and GraphQL type, and returns a
field definition, with a resolver that calls read-only L<Moo> accessors,
suitable for placing (several of) inside the hash-ref defining a type's
fields:

  sub _make_moo_field {
    my ($field_name, $type) = @_;
    ($field_name => { resolve => sub {
      my ($root_value, $args, $context, $info) = @_;
      my @passon = %$args ? ($args) : ();
      return undef unless $root_value->can($field_name);
      $root_value->$field_name(@passon);
    }, type => $type });
  }
  # ...
    fields => {
      _make_moo_field(name => $String),
      _make_moo_field(description => $String),
    },
  # ...

The code-ref will be called with these parameters:

=head4 $source

The Perl entity (possibly a blessed object) returned by the resolver
that conjured up this GraphQL object.

=head4 $args

Hash-ref of the arguments passed to the field. The values will be
Perl values.

=head4 $context

The "context" value supplied to the call to
L<GraphQL::Execution/execute>. Can be used for authenticated user
information, or a per-request cache.

=head4 $info

A hash-ref describing this node of the request; see L</info hash> below.

=head3 info hash

=head4 field_name

The real name of this field.

=head4 field_nodes

The array of Abstract Syntax Tree (AST) nodes that refer to this field
in this "selection set" (set of fields) on this object. There may be
more than one such set for a given field, if it is requested more
than once with a given name (not with an alias) - the results will
be combined into one reply.

=head4 return_type

The return type.

=head4 parent_type

The type of which this field is part.

=head4 path

The hierarchy of fields from the query root to this field-resolution.

=head4 schema

L<GraphQL::Schema> object.

=head4 fragments

Any fragments applying to this request.

=head4 root_value

The "root value" given to C<execute>.

=head4 operation

A hash-ref describing the operation (C<query>, etc) being executed.

=head4 variable_values

the operation's arguments, filled out with the variables hash supplied
to the request.

=head4 promise_code

A hash-ref. The relevant value supplied to the C<execute> function.

=cut

declare "FieldMapOutput", as Map[
  StrNameValid,
  Dict[
    type => ConsumerOf['GraphQL::Role::Output'],
    args => Optional[FieldMapInput],
    resolve => Optional[CodeRef],
    subscribe => Optional[CodeRef],
    directives => Optional[ArrayRef[HashRef]],
    deprecation_reason => Optional[Str],
    description => Optional[Str],
  ]
];

=head2 Int32Signed

32-bit signed integer.

=cut

declare "Int32Signed", as Int, where { $_ >= -2147483648 and $_ <= 2147483647 };

=head2 ArrayRefNonEmpty

Like L<Types::Standard/ArrayRef> but requires at least one entry.

=cut

declare "ArrayRefNonEmpty", constraint_generator => sub {
  intersection [ ArrayRef[@_], Tuple[Any, slurpy Any] ]
};

=head2 UniqueByProperty

An ArrayRef, its members' property (the one in the parameter) can occur
only once.

  use Moo;
  use GraphQL::Type::Library -all;
  has types => (
    is => 'ro',
    isa => UniqueByProperty['name'] & ArrayRef[InstanceOf['GraphQL::Type::Object']],
    required => 1,
  );

=cut

declare "UniqueByProperty",
  constraint_generator => sub {
    die "must give one property name" unless @_ == 1;
    my ($prop) = @_;
    declare as ArrayRef[HasMethods[$prop]], where {
      my %seen;
      !grep $seen{$_->$prop}++, @$_;
    }, inline_as {
      (undef, "my %seen; !grep \$seen{\$_->$prop}++, \@{$_[1]};");
    };
  };

=head2 ExpectObject

A C<Maybe[HashRef]> that produces a GraphQL-like message if it fails,
saying "found not an object".

=cut

declare "ExpectObject",
  as Maybe[HashRef],
  message { "found not an object" };

=head2 DocumentLocation

Hash-ref that has keys C<line> and C<column> which are C<Int>.

=cut

declare "DocumentLocation",
  as Dict[
    line => Int,
    column => Int,
  ];

=head2 JSONable

A value that will be JSON-able.

=cut

declare "JSONable",
  as Any,
    where { $JSON->encode($_); 1 };

=head2 ErrorResult

Hash-ref that has keys C<message>, C<location>, C<path>, C<extensions>.

=cut

declare "ErrorResult",
  as Dict[
    message => Str,
    path => Optional[ArrayRef[Str]],
    locations => Optional[ArrayRef[DocumentLocation]],
    extensions => Optional[HashRef[JSONable]],
  ];

=head2 ExecutionResult

Hash-ref that has keys C<data> and/or C<errors>.

The C<errors>, if present, will be an array-ref of C<ErrorResult>.

The C<data> if present will be the return data, being a hash-ref whose
values are either further hashes, array-refs, or scalars. It will be
JSON-able.

=cut

declare "ExecutionResult",
  as Dict[
    data => Optional[JSONable],
    errors => Optional[ArrayRef[ErrorResult]],
  ];

=head2 ExecutionPartialResult

Hash-ref that has keys C<data> and/or C<errors>. Like L</ExecutionResult>
above, but the C<errors>, if present, will be an array-ref of
L<GraphQL::Error> objects.

=cut

declare "ExecutionPartialResult",
  as Dict[
    data => Optional[JSONable],
    errors => Optional[ArrayRef[InstanceOf['GraphQL::Error']]],
  ];

=head2 Promise

An object that has a C<then> method.

=cut

declare "Promise",
  as HasMethods[qw(then)];

=head2 PromiseCode

A hash-ref with three keys: C<resolve>, C<all>, C<reject>. The values are
all code-refs that take one value (for C<all>, an array-ref), and create
the given kind of Promise.

An example, enabling interoperation with L<Promises>:

  use Promises qw(collect resolved rejected);
  {
    all     => \&collect,
    resolve => \&resolved,
    reject  => \&rejected,
  },

Must also have a C<new> key for use with L<GraphQL::Subscription>,
with code returning a promise that can then have C<resolve> or C<reject>
called on it.

=cut

declare "PromiseCode",
  as Dict[
    resolve => CodeLike,
    all => CodeLike,
    reject => CodeLike,
    new => Optional[CodeLike],
  ];

=head2 AsyncIterator

An instance of L<GraphQL::AsyncIterator>.

=cut

declare "AsyncIterator",
  as InstanceOf['GraphQL::AsyncIterator'];

=head1 AUTHOR

Ed J, C<< <etj at cpan.org> >>

=cut

1;