/
directives.test.ts
1525 lines (1336 loc) · 40.5 KB
/
directives.test.ts
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import crypto from 'crypto';
import {
ExecutionResult,
GraphQLArgument,
GraphQLEnumType,
GraphQLEnumValue,
GraphQLField,
GraphQLID,
GraphQLInputField,
GraphQLInputObjectType,
GraphQLObjectType,
GraphQLScalarType,
GraphQLSchema,
GraphQLString,
StringValueNode,
defaultFieldResolver,
graphql,
GraphQLNonNull,
GraphQLList,
GraphQLUnionType,
GraphQLInt,
GraphQLOutputType,
isNonNullType,
isScalarType,
isListType,
TypeSystemExtensionNode,
} from 'graphql';
import formatDate from 'dateformat';
import { makeExecutableSchema } from '../generate/index';
import { VisitableSchemaType } from '../Interfaces';
import {
SchemaDirectiveVisitor,
SchemaVisitor,
visitSchema,
graphqlVersion,
} from '../utils/index';
const typeDefs = `
directive @schemaDirective(role: String) on SCHEMA
directive @schemaExtensionDirective(role: String) on SCHEMA
directive @queryTypeDirective on OBJECT
directive @queryTypeExtensionDirective on OBJECT
directive @queryFieldDirective on FIELD_DEFINITION
directive @enumTypeDirective on ENUM
directive @enumTypeExtensionDirective on ENUM
directive @enumValueDirective on ENUM_VALUE
directive @dateDirective(tz: String) on SCALAR
directive @dateExtensionDirective(tz: String) on SCALAR
directive @interfaceDirective on INTERFACE
directive @interfaceExtensionDirective on INTERFACE
directive @interfaceFieldDirective on FIELD_DEFINITION
directive @inputTypeDirective on INPUT_OBJECT
directive @inputTypeExtensionDirective on INPUT_OBJECT
directive @inputFieldDirective on INPUT_FIELD_DEFINITION
directive @mutationTypeDirective on OBJECT
directive @mutationTypeExtensionDirective on OBJECT
directive @mutationArgumentDirective on ARGUMENT_DEFINITION
directive @mutationMethodDirective on FIELD_DEFINITION
directive @objectTypeDirective on OBJECT
directive @objectTypeExtensionDirective on OBJECT
directive @objectFieldDirective on FIELD_DEFINITION
directive @unionDirective on UNION
directive @unionExtensionDirective on UNION
schema @schemaDirective(role: "admin") {
query: Query
mutation: Mutation
}
${
graphqlVersion() >= 14
? 'extend schema @schemaExtensionDirective(role: "admin")'
: ''
}
type Query @queryTypeDirective {
people: [Person] @queryFieldDirective
}
${
graphqlVersion() >= 13 ? 'extend type Query @queryTypeExtensionDirective' : ''
}
enum Gender @enumTypeDirective {
NONBINARY @enumValueDirective
FEMALE
MALE
}
${
graphqlVersion() >= 14 ? 'extend enum Gender @enumTypeExtensionDirective' : ''
}
scalar Date @dateDirective(tz: "utc")
${
graphqlVersion() >= 14
? 'extend scalar Date @dateExtensionDirective(tz: "utc")'
: ''
}
interface Named @interfaceDirective {
name: String! @interfaceFieldDirective
}
${
graphqlVersion() >= 13
? 'extend interface Named @interfaceExtensionDirective'
: ''
}
input PersonInput @inputTypeDirective {
name: String! @inputFieldDirective
gender: Gender
}
${
graphqlVersion() >= 14
? 'extend input PersonInput @inputTypeExtensionDirective'
: ''
}
type Mutation @mutationTypeDirective {
addPerson(
input: PersonInput @mutationArgumentDirective
): Person @mutationMethodDirective
}
${
graphqlVersion() >= 13
? 'extend type Mutation @mutationTypeExtensionDirective'
: ''
}
type Person implements Named @objectTypeDirective {
id: ID! @objectFieldDirective
name: String!
}
${
graphqlVersion() >= 14
? 'extend type Person @objectTypeExtensionDirective'
: ''
}
union WhateverUnion @unionDirective = Person | Query | Mutation
${
graphqlVersion() >= 14
? 'extend union WhateverUnion @unionExtensionDirective'
: ''
}
`;
describe('@directives', () => {
test('are included in the schema AST', () => {
const schema = makeExecutableSchema({
typeDefs,
resolvers: {
Gender: {
NONBINARY: 'NB',
FEMALE: 'F',
MALE: 'M',
},
},
});
function checkDirectives(
type: VisitableSchemaType,
typeDirectiveNames: Array<string>,
fieldDirectiveMap: Record<string, Array<string>> = {},
) {
expect(getDirectiveNames(type)).toEqual(typeDirectiveNames);
Object.keys(fieldDirectiveMap).forEach((key) => {
expect(
getDirectiveNames((type as GraphQLObjectType).getFields()[key]),
).toEqual(fieldDirectiveMap[key]);
});
}
function getDirectiveNames(type: VisitableSchemaType): Array<string> {
let directives = type.astNode.directives.map((d) => d.name.value);
const extensionASTNodes = (type as {
extensionASTNodes?: Array<TypeSystemExtensionNode>;
}).extensionASTNodes;
if (extensionASTNodes != null) {
extensionASTNodes.forEach((extensionASTNode) => {
directives = directives.concat(
extensionASTNode.directives.map((d) => d.name.value),
);
});
}
return directives;
}
expect(getDirectiveNames(schema)).toEqual(
graphqlVersion() >= 14
? ['schemaDirective', 'schemaExtensionDirective']
: ['schemaDirective'],
);
checkDirectives(
schema.getQueryType(),
graphqlVersion() >= 13
? ['queryTypeDirective', 'queryTypeExtensionDirective']
: ['queryTypeDirective'],
{
people: ['queryFieldDirective'],
},
);
expect(getDirectiveNames(schema.getType('Gender'))).toEqual(
graphqlVersion() >= 14
? ['enumTypeDirective', 'enumTypeExtensionDirective']
: ['enumTypeDirective'],
);
const nonBinary = (schema.getType(
'Gender',
) as GraphQLEnumType).getValues()[0];
expect(getDirectiveNames(nonBinary)).toEqual(['enumValueDirective']);
checkDirectives(
schema.getType('Date') as GraphQLObjectType,
graphqlVersion() >= 14
? ['dateDirective', 'dateExtensionDirective']
: ['dateDirective'],
);
checkDirectives(
schema.getType('Named') as GraphQLObjectType,
graphqlVersion() >= 13
? ['interfaceDirective', 'interfaceExtensionDirective']
: ['interfaceDirective'],
{
name: ['interfaceFieldDirective'],
},
);
checkDirectives(
schema.getType('PersonInput') as GraphQLObjectType,
graphqlVersion() >= 14
? ['inputTypeDirective', 'inputTypeExtensionDirective']
: ['inputTypeDirective'],
{
name: ['inputFieldDirective'],
gender: [],
},
);
checkDirectives(
schema.getMutationType(),
graphqlVersion() >= 13
? ['mutationTypeDirective', 'mutationTypeExtensionDirective']
: ['mutationTypeDirective'],
{
addPerson: ['mutationMethodDirective'],
},
);
expect(
getDirectiveNames(schema.getMutationType().getFields().addPerson.args[0]),
).toEqual(['mutationArgumentDirective']);
checkDirectives(
schema.getType('Person'),
graphqlVersion() >= 14
? ['objectTypeDirective', 'objectTypeExtensionDirective']
: ['objectTypeDirective'],
{
id: ['objectFieldDirective'],
name: [],
},
);
checkDirectives(
schema.getType('WhateverUnion'),
graphqlVersion() >= 14
? ['unionDirective', 'unionExtensionDirective']
: ['unionDirective'],
);
});
test('works with enum and its resolvers', () => {
const schema = makeExecutableSchema({
typeDefs: `
enum DateFormat {
LOCAL
ISO
}
directive @date(format: DateFormat) on FIELD_DEFINITION
scalar Date
type Query {
today: Date @date(format: LOCAL)
}
`,
resolvers: {
DateFormat: {
LOCAL: 'local',
ISO: 'iso',
},
},
});
expect(schema.getType('DateFormat')).toBeDefined();
expect(schema.getDirectives()).toHaveLength(4);
expect(schema.getDirective('date')).toBeDefined();
});
test('can be implemented with SchemaDirectiveVisitor', () => {
const visited: Set<GraphQLObjectType> = new Set();
const schema = makeExecutableSchema({ typeDefs });
SchemaDirectiveVisitor.visitSchemaDirectives(schema, {
// The directive subclass can be defined anonymously inline!
queryTypeDirective: class extends SchemaDirectiveVisitor {
public static description = 'A @directive for query object types';
public visitObject(object: GraphQLObjectType) {
expect(object).toBe(schema.getQueryType());
visited.add(object);
}
},
queryTypeExtensionDirective: class extends SchemaDirectiveVisitor {
public static description = 'A @directive for query object types';
public visitObject(object: GraphQLObjectType) {
expect(object).toBe(schema.getQueryType());
visited.add(object);
}
},
});
expect(visited.size).toBe(1);
});
test('can visit the schema itself', () => {
const visited: Array<GraphQLSchema> = [];
const schema = makeExecutableSchema({ typeDefs });
SchemaDirectiveVisitor.visitSchemaDirectives(schema, {
schemaDirective: class extends SchemaDirectiveVisitor {
public visitSchema(s: GraphQLSchema) {
visited.push(s);
}
},
schemaExtensionDirective: class extends SchemaDirectiveVisitor {
public visitSchema(s: GraphQLSchema) {
visited.push(s);
}
},
});
expect(visited.length).toBe(graphqlVersion() >= 14 ? 2 : 1);
expect(visited[0]).toBe(schema);
if (graphqlVersion() >= 14) {
expect(visited[1]).toBe(schema);
}
});
test('can visit fields within object types', () => {
const schema = makeExecutableSchema({ typeDefs });
let mutationObjectType: GraphQLObjectType;
let mutationField: GraphQLField<any, any>;
let enumObjectType: GraphQLEnumType;
let inputObjectType: GraphQLInputObjectType;
SchemaDirectiveVisitor.visitSchemaDirectives(schema, {
mutationTypeDirective: class extends SchemaDirectiveVisitor {
public visitObject(object: GraphQLObjectType) {
mutationObjectType = object;
expect(this.visitedType).toBe(object);
expect(object.name).toBe('Mutation');
}
},
mutationTypeExtensionDirective: class extends SchemaDirectiveVisitor {
public visitObject(object: GraphQLObjectType) {
mutationObjectType = object;
expect(this.visitedType).toBe(object);
expect(object.name).toBe('Mutation');
}
},
mutationMethodDirective: class extends SchemaDirectiveVisitor {
public visitFieldDefinition(
field: GraphQLField<any, any>,
details: {
objectType: GraphQLObjectType;
},
) {
expect(this.visitedType).toBe(field);
expect(field.name).toBe('addPerson');
expect(details.objectType).toBe(mutationObjectType);
expect(field.args.length).toBe(1);
mutationField = field;
}
},
mutationArgumentDirective: class extends SchemaDirectiveVisitor {
public visitArgumentDefinition(
arg: GraphQLArgument,
details: {
field: GraphQLField<any, any>;
objectType: GraphQLObjectType;
},
) {
expect(this.visitedType).toBe(arg);
expect(arg.name).toBe('input');
expect(details.field).toBe(mutationField);
expect(details.objectType).toBe(mutationObjectType);
expect(details.field.args[0]).toBe(arg);
}
},
enumTypeDirective: class extends SchemaDirectiveVisitor {
public visitEnum(enumType: GraphQLEnumType) {
expect(this.visitedType).toBe(enumType);
expect(enumType.name).toBe('Gender');
enumObjectType = enumType;
}
},
enumTypeExtensionDirective: class extends SchemaDirectiveVisitor {
public visitEnum(enumType: GraphQLEnumType) {
expect(this.visitedType).toBe(enumType);
expect(enumType.name).toBe('Gender');
enumObjectType = enumType;
}
},
enumValueDirective: class extends SchemaDirectiveVisitor {
public visitEnumValue(
value: GraphQLEnumValue,
details: {
enumType: GraphQLEnumType;
},
) {
expect(this.visitedType).toBe(value);
expect(value.name).toBe('NONBINARY');
expect(value.value).toBe('NONBINARY');
expect(details.enumType).toBe(enumObjectType);
}
},
inputTypeDirective: class extends SchemaDirectiveVisitor {
public visitInputObject(object: GraphQLInputObjectType) {
inputObjectType = object;
expect(this.visitedType).toBe(object);
expect(object.name).toBe('PersonInput');
}
},
inputTypeExtensionDirective: class extends SchemaDirectiveVisitor {
public visitInputObject(object: GraphQLInputObjectType) {
inputObjectType = object;
expect(this.visitedType).toBe(object);
expect(object.name).toBe('PersonInput');
}
},
inputFieldDirective: class extends SchemaDirectiveVisitor {
public visitInputFieldDefinition(
field: GraphQLInputField,
details: {
objectType: GraphQLInputObjectType;
},
) {
expect(this.visitedType).toBe(field);
expect(field.name).toBe('name');
expect(details.objectType).toBe(inputObjectType);
}
},
});
});
test('can check if a visitor method is implemented', () => {
class Visitor extends SchemaVisitor {
// eslint-disable-next-line @typescript-eslint/no-empty-function
public notVisitorMethod() {}
public visitObject(object: GraphQLObjectType) {
return object;
}
}
expect(Visitor.implementsVisitorMethod('notVisitorMethod')).toBe(false);
expect(Visitor.implementsVisitorMethod('visitObject')).toBe(true);
expect(Visitor.implementsVisitorMethod('visitInputFieldDefinition')).toBe(
false,
);
expect(Visitor.implementsVisitorMethod('visitBogusType')).toBe(false);
});
test('can use visitSchema for simple visitor patterns', () => {
class SimpleVisitor extends SchemaVisitor {
public visitCount = 0;
public names: Array<string> = [];
constructor(s: GraphQLSchema) {
super();
this.schema = s;
}
public visit() {
// More complicated visitor implementations might use the
// visitorSelector function more selectively, but this SimpleVisitor
// class always volunteers itself to visit any schema type.
visitSchema(this.schema, () => [this]);
}
public visitObject(object: GraphQLObjectType) {
expect(this.schema.getType(object.name)).toBe(object);
this.names.push(object.name);
}
}
const schema = makeExecutableSchema({ typeDefs });
const visitor = new SimpleVisitor(schema);
visitor.visit();
expect(visitor.names.sort((a, b) => a.localeCompare(b))).toEqual([
'Mutation',
'Person',
'Query',
]);
});
test('can use SchemaDirectiveVisitor as a no-op visitor', () => {
const schema = makeExecutableSchema({ typeDefs });
const methodNamesEncountered = Object.create(null);
class EnthusiasticVisitor extends SchemaDirectiveVisitor {
public static implementsVisitorMethod(name: string) {
// Pretend this class implements all visitor methods. This is safe
// because the SchemaVisitor base class provides empty stubs for all
// the visitor methods that might be called.
methodNamesEncountered[name] = true;
return methodNamesEncountered[name];
}
}
EnthusiasticVisitor.visitSchemaDirectives(schema, {
schemaDirective: EnthusiasticVisitor,
queryTypeDirective: EnthusiasticVisitor,
queryFieldDirective: EnthusiasticVisitor,
enumTypeDirective: EnthusiasticVisitor,
enumValueDirective: EnthusiasticVisitor,
dateDirective: EnthusiasticVisitor,
interfaceDirective: EnthusiasticVisitor,
interfaceFieldDirective: EnthusiasticVisitor,
inputTypeDirective: EnthusiasticVisitor,
inputFieldDirective: EnthusiasticVisitor,
mutationTypeDirective: EnthusiasticVisitor,
mutationArgumentDirective: EnthusiasticVisitor,
mutationMethodDirective: EnthusiasticVisitor,
objectTypeDirective: EnthusiasticVisitor,
objectFieldDirective: EnthusiasticVisitor,
unionDirective: EnthusiasticVisitor,
});
expect(
Object.keys(methodNamesEncountered).sort((a, b) => a.localeCompare(b)),
).toEqual(
Object.keys(SchemaVisitor.prototype)
.filter((name) => name.startsWith('visit'))
.sort((a, b) => a.localeCompare(b)),
);
});
test('can handle declared arguments', () => {
const schemaText = `
directive @oyez(
times: Int = 5,
party: Party = IMPARTIAL,
) on OBJECT | FIELD_DEFINITION
schema {
query: Courtroom
}
type Courtroom @oyez {
judge: String @oyez(times: 0)
marshall: String @oyez
}
enum Party {
DEFENSE
PROSECUTION
IMPARTIAL
}`;
const schema = makeExecutableSchema({ typeDefs: schemaText });
const context = {
objectCount: 0,
fieldCount: 0,
};
const visitors = SchemaDirectiveVisitor.visitSchemaDirectives(
schema,
{
oyez: class extends SchemaDirectiveVisitor {
public static getDirectiveDeclaration(
name: string,
theSchema: GraphQLSchema,
) {
expect(theSchema).toBe(schema);
const prev = schema.getDirective(name);
prev.args.some((arg) => {
if (arg.name === 'times') {
// Override the default value of the times argument to be 3
// instead of 5.
arg.defaultValue = 3;
return true;
}
return false;
});
return prev;
}
public visitObject() {
++this.context.objectCount;
expect(this.args.times).toBe(3);
}
public visitFieldDefinition(field: GraphQLField<any, any>) {
++this.context.fieldCount;
if (field.name === 'judge') {
expect(this.args.times).toBe(0);
} else if (field.name === 'marshall') {
expect(this.args.times).toBe(3);
}
expect(this.args.party).toBe('IMPARTIAL');
}
},
},
context,
);
expect(context.objectCount).toBe(1);
expect(context.fieldCount).toBe(2);
expect(Object.keys(visitors)).toEqual(['oyez']);
expect(
visitors.oyez.map(
(v) =>
(v.visitedType as GraphQLObjectType | GraphQLField<any, any>).name,
),
).toEqual(['Courtroom', 'judge', 'marshall']);
});
test('can be used to implement the @upper example', () => {
const schema = makeExecutableSchema({
typeDefs: `
directive @upper on FIELD_DEFINITION
type Query {
hello: String @upper
}`,
schemaDirectives: {
upper: class extends SchemaDirectiveVisitor {
public visitFieldDefinition(field: GraphQLField<any, any>) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (...args) {
const result = await resolve.apply(this, args);
if (typeof result === 'string') {
return result.toUpperCase();
}
return result;
};
}
},
},
resolvers: {
Query: {
hello() {
return 'hello world';
},
},
},
});
return graphql(
schema,
`
query {
hello
}
`,
).then(({ data }) => {
expect(data).toEqual({
hello: 'HELLO WORLD',
});
});
});
test('can be used to implement the @date example', () => {
const schema = makeExecutableSchema({
typeDefs: `
directive @date(format: String) on FIELD_DEFINITION
scalar Date
type Query {
today: Date @date(format: "mmmm d, yyyy")
}`,
schemaDirectives: {
date: class extends SchemaDirectiveVisitor {
public visitFieldDefinition(field: GraphQLField<any, any>) {
const { resolve = defaultFieldResolver } = field;
const { format } = this.args;
field.type = GraphQLString;
field.resolve = async function (...args) {
const date = await resolve.apply(this, args);
return formatDate(date, format, true);
};
}
},
},
resolvers: {
Query: {
today() {
return new Date(1519688273858).toUTCString();
},
},
},
});
return graphql(
schema,
`
query {
today
}
`,
).then(({ data }) => {
expect(data).toEqual({
today: 'February 26, 2018',
});
});
});
test('can be used to implement the @date by adding an argument', async () => {
class FormattableDateDirective extends SchemaDirectiveVisitor {
public visitFieldDefinition(field: GraphQLField<any, any>) {
const { resolve = defaultFieldResolver } = field;
const { defaultFormat } = this.args;
field.args.push(
Object.create({
name: 'format',
type: GraphQLString,
}),
);
field.type = GraphQLString;
field.resolve = async function (
source,
{ format, ...args },
context,
info,
) {
const newFormat = format || defaultFormat;
const date = await resolve.call(this, source, args, context, info);
return formatDate(date, newFormat, true);
};
}
}
const schema = makeExecutableSchema({
typeDefs: `
directive @date(
defaultFormat: String = "mmmm d, yyyy"
) on FIELD_DEFINITION
scalar Date
type Query {
today: Date @date
}`,
schemaDirectives: {
date: FormattableDateDirective,
},
resolvers: {
Query: {
today() {
return new Date(1521131357195);
},
},
},
});
const resultNoArg = await graphql(schema, 'query { today }');
if (resultNoArg.errors != null) {
expect(resultNoArg.errors).toEqual([]);
}
expect(resultNoArg.data).toEqual({ today: 'March 15, 2018' });
const resultWithArg = await graphql(
schema,
`
query {
today(format: "dd mmm yyyy")
}
`,
);
if (resultWithArg.errors != null) {
expect(resultWithArg.errors).toEqual([]);
}
expect(resultWithArg.data).toEqual({ today: '15 Mar 2018' });
});
test('can be used to implement the @intl example', () => {
function translate(text: string, path: Array<string>, locale: string) {
expect(text).toBe('hello');
expect(path).toEqual(['Query', 'greeting']);
expect(locale).toBe('fr');
return 'bonjour';
}
const context = {
locale: 'fr',
};
const schema = makeExecutableSchema({
typeDefs: `
directive @intl on FIELD_DEFINITION
type Query {
greeting: String @intl
}`,
schemaDirectives: {
intl: class extends SchemaDirectiveVisitor {
public visitFieldDefinition(
field: GraphQLField<any, any>,
details: {
objectType: GraphQLObjectType;
},
) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (...args: Array<any>) {
const defaultText = await resolve.apply(this, args);
// In this example, path would be ["Query", "greeting"]:
const path = [details.objectType.name, field.name];
expect(args[2]).toBe(context);
return translate(defaultText, path, context.locale);
};
}
},
},
resolvers: {
Query: {
greeting() {
return 'hello';
},
},
},
});
return graphql(
schema,
`
query {
greeting
}
`,
null,
context,
).then(({ data }) => {
expect(data).toEqual({
greeting: 'bonjour',
});
});
});
test('can be used to implement the @auth example', async () => {
const roles = ['UNKNOWN', 'USER', 'REVIEWER', 'ADMIN'];
function getUser(token: string) {
return {
hasRole(role: string) {
const tokenIndex = roles.indexOf(token);
const roleIndex = roles.indexOf(role);
return roleIndex >= 0 && tokenIndex >= roleIndex;
},
};
}
class AuthDirective extends SchemaDirectiveVisitor {
public visitObject(type: GraphQLObjectType) {
this.ensureFieldsWrapped(type);
(type as any)._requiredAuthRole = this.args.requires;
}
// Visitor methods for nested types like fields and arguments
// also receive a details object that provides information about
// the parent and grandparent types.
public visitFieldDefinition(
field: GraphQLField<any, any>,
details: { objectType: GraphQLObjectType },
) {
this.ensureFieldsWrapped(details.objectType);
(field as any)._requiredAuthRole = this.args.requires;
}
public ensureFieldsWrapped(objectType: GraphQLObjectType) {
// Mark the GraphQLObjectType object to avoid re-wrapping:
if ((objectType as any)._authFieldsWrapped) {
return;
}
(objectType as any)._authFieldsWrapped = true;
const fields = objectType.getFields();
Object.keys(fields).forEach((fieldName) => {
const field = fields[fieldName];
const { resolve = defaultFieldResolver } = field;
field.resolve = function (...args: Array<any>) {
// Get the required Role from the field first, falling back
// to the objectType if no Role is required by the field:
const requiredRole =
(field as any)._requiredAuthRole ||
(objectType as any)._requiredAuthRole;
if (!requiredRole) {
return resolve.apply(this, args);
}
const context = args[2];
const user = getUser(context.headers.authToken);
if (!user.hasRole(requiredRole)) {
throw new Error('not authorized');
}
return resolve.apply(this, args);
};
});
}
}
const schema = makeExecutableSchema({
typeDefs: `
directive @auth(
requires: Role = ADMIN,
) on OBJECT | FIELD_DEFINITION
enum Role {
ADMIN
REVIEWER
USER
UNKNOWN
}
type User @auth(requires: USER) {
name: String
banned: Boolean @auth(requires: ADMIN)
canPost: Boolean @auth(requires: REVIEWER)
}
type Query {
users: [User]
}`,
schemaDirectives: {
auth: AuthDirective,
},
resolvers: {
Query: {
users() {
return [
{
banned: true,
canPost: false,
name: 'Ben',
},
];
},
},
},
});
function execWithRole(role: string): Promise<ExecutionResult> {
return graphql(
schema,
`