/
ApolloServer.ts
3475 lines (3027 loc) 路 111 KB
/
ApolloServer.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 http from 'http';
import { sha256 } from 'js-sha256';
import { URL } from 'url';
import express = require('express');
import bodyParser = require('body-parser');
import { Report, Trace } from 'apollo-reporting-protobuf';
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLError,
ValidationContext,
FieldDefinitionNode,
getIntrospectionQuery,
} from 'graphql';
import { PubSub } from 'graphql-subscriptions';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import WebSocket from 'ws';
import { execute } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import {
createPersistedQueryLink as createPersistedQuery,
VERSION,
} from 'apollo-link-persisted-queries';
import {
createApolloFetch,
ApolloFetch,
GraphQLRequest,
ParsedResponse,
} from 'apollo-fetch';
import {
AuthenticationError,
UserInputError,
gql,
Config,
ApolloServerBase,
PluginDefinition,
GraphQLService,
GraphQLExecutor,
ApolloServerPluginInlineTrace,
ApolloServerPluginUsageReporting,
ApolloServerPluginUsageReportingOptions,
GraphQLServiceConfig,
} from 'apollo-server-core';
import { GraphQLExtension, GraphQLResponse } from 'graphql-extensions';
import { TracingFormat } from 'apollo-tracing';
import ApolloServerPluginResponseCache from 'apollo-server-plugin-response-cache';
import { GraphQLRequestContext } from 'apollo-server-types';
import { mockDate, unmockDate, advanceTimeBy } from '../../../__mocks__/date';
export function createServerInfo<AS extends ApolloServerBase>(
server: AS,
httpServer: http.Server,
): ServerInfo<AS> {
const serverInfo: any = {
...httpServer.address(),
server,
httpServer,
};
// Convert IPs which mean "any address" (IPv4 or IPv6) into localhost
// corresponding loopback ip. Note that the url field we're setting is
// primarily for consumption by our test suite. If this heuristic is wrong for
// your use case, explicitly specify a frontend host (in the `host` option to
// ApolloServer.listen).
let hostForUrl = serverInfo.address;
if (serverInfo.address === '' || serverInfo.address === '::')
hostForUrl = 'localhost';
serverInfo.url = require('url').format({
protocol: 'http',
hostname: hostForUrl,
port: serverInfo.port,
pathname: server.graphqlPath,
});
return serverInfo;
}
const INTROSPECTION_QUERY = `
{
__schema {
directives {
name
}
}
}
`;
const TEST_STRING_QUERY = `
{
testString
}
`;
const queryType = new GraphQLObjectType({
name: 'QueryType',
fields: {
testString: {
type: GraphQLString,
resolve() {
return 'test string';
},
},
},
});
const schema = new GraphQLSchema({
query: queryType,
});
const makeGatewayMock = ({
optionsSpy = _options => {},
unsubscribeSpy = () => {},
executor = () => ({}),
}: {
optionsSpy?: (_options: any) => void;
unsubscribeSpy?: () => void;
executor?: GraphQLExecutor;
} = {}) => {
let resolution: GraphQLServiceConfig | null = null;
let rejection: Error | null = null;
const eventuallyAssigned = {
resolveLoad: (config: GraphQLServiceConfig) => {
resolution = config;
},
rejectLoad: (err: Error) => {
rejection = err;
},
triggerSchemaChange: null as (newSchema) => void,
};
const mockedGateway: GraphQLService = {
executor,
load: async (options) => {
optionsSpy(options);
// Make sure it's async
await new Promise(res => setImmediate(res));
if (rejection) {
throw rejection;
}
if (resolution) {
return resolution;
}
throw Error("Neither resolving nor rejecting?");
},
onSchemaChange: callback => {
eventuallyAssigned.triggerSchemaChange = callback;
return unsubscribeSpy;
},
};
return { gateway: mockedGateway, triggers: eventuallyAssigned };
};
export interface ServerInfo<AS extends ApolloServerBase> {
address: string;
family: string;
url: string;
port: number | string;
server: AS;
httpServer: http.Server;
}
export interface CreateServerFunc<AS extends ApolloServerBase> {
(config: Config, suppressStartCall?: boolean): Promise<ServerInfo<AS>>;
}
export interface StopServerFunc {
(): Promise<void>;
}
export function testApolloServer<AS extends ApolloServerBase>(
createApolloServer: CreateServerFunc<AS>,
stopServer: StopServerFunc,
) {
describe('ApolloServer', () => {
afterEach(stopServer);
describe('constructor', () => {
describe('validation rules', () => {
it('accepts additional rules', async () => {
const NoTestString = (context: ValidationContext) => ({
Field(node: FieldDefinitionNode) {
if (node.name.value === 'testString') {
context.reportError(
new GraphQLError('Not allowed to use', [node]),
);
}
},
});
const formatError = jest.fn(error => {
expect(error instanceof Error).toBe(true);
return error;
});
const { url: uri } = await createApolloServer({
schema,
validationRules: [NoTestString],
introspection: false,
formatError,
});
const apolloFetch = createApolloFetch({ uri });
const introspectionResult = await apolloFetch({
query: INTROSPECTION_QUERY,
});
expect(introspectionResult.data).toBeUndefined();
expect(introspectionResult.errors).toBeDefined();
expect(introspectionResult.errors[0].message).toMatch(
/introspection/,
);
expect(formatError.mock.calls.length).toEqual(
introspectionResult.errors.length,
);
const result = await apolloFetch({ query: TEST_STRING_QUERY });
expect(result.data).toBeUndefined();
expect(result.errors).toBeDefined();
expect(result.errors[0].message).toMatch(/Not allowed/);
expect(formatError.mock.calls.length).toEqual(
introspectionResult.errors.length + result.errors.length,
);
});
it('allows introspection by default', async () => {
const nodeEnv = process.env.NODE_ENV;
delete process.env.NODE_ENV;
const { url: uri } = await createApolloServer({
schema,
stopOnTerminationSignals: false,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: INTROSPECTION_QUERY });
expect(result.data).toBeDefined();
expect(result.errors).toBeUndefined();
process.env.NODE_ENV = nodeEnv;
});
it('prevents introspection by default during production', async () => {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
const { url: uri } = await createApolloServer({
schema,
stopOnTerminationSignals: false,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: INTROSPECTION_QUERY });
expect(result.data).toBeUndefined();
expect(result.errors).toBeDefined();
expect(result.errors.length).toEqual(1);
expect(result.errors[0].extensions.code).toEqual(
'GRAPHQL_VALIDATION_FAILED',
);
process.env.NODE_ENV = nodeEnv;
});
it('allows introspection to be enabled explicitly', async () => {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
const { url: uri } = await createApolloServer({
schema,
introspection: true,
stopOnTerminationSignals: false,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: INTROSPECTION_QUERY });
expect(result.data).toBeDefined();
expect(result.errors).toBeUndefined();
process.env.NODE_ENV = nodeEnv;
});
it('prohibits providing a gateway in addition to schema/typedefs/resolvers', async () => {
const { gateway } = makeGatewayMock();
const incompatibleArgsSpy = jest.fn();
await createApolloServer({ gateway, schema }).catch(err =>
incompatibleArgsSpy(err.message),
);
expect(incompatibleArgsSpy.mock.calls[0][0]).toMatch(
/Cannot define both/,
);
await createApolloServer({ gateway, modules: {} as any }).catch(err =>
incompatibleArgsSpy(err.message),
);
expect(incompatibleArgsSpy.mock.calls[1][0]).toMatch(
/Cannot define both/,
);
await createApolloServer({ gateway, typeDefs: {} as any }).catch(
err => incompatibleArgsSpy(err.message),
);
expect(incompatibleArgsSpy.mock.calls[2][0]).toMatch(
/Cannot define both/,
);
});
it('prohibits providing a gateway in addition to subscription options', async () => {
const { gateway } = makeGatewayMock();
const expectedError =
'Subscriptions are not yet compatible with the gateway';
const incompatibleArgsSpy = jest.fn();
await createApolloServer({
gateway,
subscriptions: 'pathToSubscriptions',
}).catch(err => incompatibleArgsSpy(err.message));
expect(incompatibleArgsSpy.mock.calls[0][0]).toMatch(expectedError);
await createApolloServer({
gateway,
subscriptions: true as any,
}).catch(err => incompatibleArgsSpy(err.message));
expect(incompatibleArgsSpy.mock.calls[1][0]).toMatch(expectedError);
await createApolloServer({
gateway,
subscriptions: { path: '' } as any,
}).catch(err => incompatibleArgsSpy(err.message));
expect(incompatibleArgsSpy.mock.calls[2][0]).toMatch(expectedError);
await createApolloServer({
gateway,
}).catch(err => incompatibleArgsSpy(err.message));
expect(incompatibleArgsSpy.mock.calls[3][0]).toMatch(expectedError);
});
});
it('variable coercion errors', async () => {
const { url: uri } = await createApolloServer({
typeDefs: gql`
type Query {
hello(x: String): String
}
`,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({
query: `query ($x:String) {hello(x:$x)}`,
variables: { x: 2 },
});
expect(result.data).toBeUndefined();
expect(result.errors).toBeDefined();
expect(result.errors[0].message).toMatch(/got invalid value 2; Expected type String/);
expect(result.errors[0].extensions.code).toBe('BAD_USER_INPUT');
});
describe('schema creation', () => {
it('accepts typeDefs and resolvers', async () => {
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = { Query: { hello: () => 'hi' } };
const { url: uri } = await createApolloServer({
typeDefs,
resolvers,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: '{hello}' });
expect(result.data).toEqual({ hello: 'hi' });
expect(result.errors).toBeUndefined();
});
it("accepts a gateway's schema and calls its executor", async () => {
const executor = jest.fn();
executor.mockReturnValue(
Promise.resolve({ data: { testString: 'hi - but federated!' } }),
);
const { gateway, triggers } = makeGatewayMock({ executor });
triggers.resolveLoad({ schema, executor });
const { url: uri } = await createApolloServer({
gateway,
subscriptions: false,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: '{testString}' });
expect(result.data).toEqual({ testString: 'hi - but federated!' });
expect(result.errors).toBeUndefined();
expect(executor).toHaveBeenCalled();
});
it("rejected load promise is thrown by server.start", async () => {
const { gateway, triggers } = makeGatewayMock();
const loadError = new Error("load error which should be be thrown by start");
triggers.rejectLoad(loadError);
expect(createApolloServer({
gateway,
subscriptions: false,
})).rejects.toThrowError(loadError);
});
it("rejected load promise acts as an error boundary", async () => {
const executor = jest.fn();
executor.mockResolvedValueOnce(
{ data: { testString: 'should not get this' } }
);
executor.mockRejectedValueOnce(
{ errors: [{errorWhichShouldNot: "ever be triggered"}] }
);
const consoleErrorSpy =
jest.spyOn(console, 'error').mockImplementation();
const { gateway, triggers } = makeGatewayMock({ executor });
triggers.rejectLoad(new Error("load error which should be masked"));
const { url: uri } = await createApolloServer({
gateway,
subscriptions: false,
}, true);
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: '{testString}' });
expect(result.data).toBeUndefined();
expect(result.errors).toContainEqual(
expect.objectContaining({
extensions: expect.objectContaining({
code: "INTERNAL_SERVER_ERROR",
}),
message: "This data graph is missing a valid configuration. " +
"More details may be available in the server logs."
})
);
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Apollo Server was started implicitly and an error occurred during startup. ' +
'(Consider calling `await server.start()` immediately after ' +
'`server = new ApolloServer()` so you can handle these errors directly before ' +
'starting your web server.) All GraphQL requests will now fail. The startup error ' +
'was: ' +
'load error which should be masked',
);
expect(executor).not.toHaveBeenCalled();
});
it('uses schema over resolvers + typeDefs', async () => {
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = { Query: { hello: () => 'hi' } };
const { url: uri } = await createApolloServer({
typeDefs,
resolvers,
schema,
});
const apolloFetch = createApolloFetch({ uri });
const typeDefResult = await apolloFetch({ query: '{hello}' });
expect(typeDefResult.data).toBeUndefined();
expect(typeDefResult.errors).toBeDefined();
const result = await apolloFetch({ query: '{testString}' });
expect(result.data).toEqual({ testString: 'test string' });
expect(result.errors).toBeUndefined();
});
it('allows mocks as boolean', async () => {
const typeDefs = gql`
type Query {
hello: String
}
`;
const { url: uri } = await createApolloServer({
typeDefs,
mocks: true,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: '{hello}' });
expect(result.data).toEqual({ hello: 'Hello World' });
expect(result.errors).toBeUndefined();
});
it('allows mocks as an object', async () => {
const typeDefs = gql`
type Query {
hello: String
}
`;
const { url: uri } = await createApolloServer({
typeDefs,
mocks: { String: () => 'mock city' },
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: '{hello}' });
expect(result.data).toEqual({ hello: 'mock city' });
expect(result.errors).toBeUndefined();
});
it('allows mocks as an object without overriding the existing resolvers', async () => {
const typeDefs = gql`
type User {
first: String
last: String
}
type Query {
user: User
}
`;
const resolvers = {
Query: {
user: () => ({
first: 'James',
last: 'Heinlen',
}),
},
};
const { url: uri } = await createApolloServer({
typeDefs,
resolvers,
mocks: {
User: () => ({
last: () => 'mock city',
}),
},
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({
query: '{user{first last}}',
});
expect(result.data).toEqual({
user: { first: 'Hello World', last: 'mock city' },
});
expect(result.errors).toBeUndefined();
});
// Need to fix bug in graphql-tools to enable mocks to override the existing resolvers
it.skip('allows mocks as an object with overriding the existing resolvers', async () => {
const typeDefs = gql`
type User {
first: String
last: String
}
type Query {
user: User
}
`;
const resolvers = {
Query: {
user: () => ({
first: 'James',
last: 'Heinlen',
}),
},
};
const { url: uri } = await createApolloServer({
typeDefs,
resolvers,
mocks: {
User: () => ({
last: () => 'mock city',
}),
},
mockEntireSchema: false,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({
query: '{user{first last}}',
});
expect(result.data).toEqual({
user: { first: 'James', last: 'mock city' },
});
expect(result.errors).toBeUndefined();
});
});
});
describe('Plugins', () => {
let apolloFetch: ApolloFetch;
let apolloFetchResponse: ParsedResponse;
let serverInstance: ApolloServerBase;
const setupApolloServerAndFetchPairForPlugins = async (
plugins: PluginDefinition[] = [],
) => {
const { url: uri, server } = await createApolloServer({
context: { customContext: true },
typeDefs: gql`
type Query {
justAField: String
}
`,
plugins,
});
serverInstance = server;
apolloFetch = createApolloFetch({ uri })
// Store the response so we can inspect it.
.useAfter(({ response }, next) => {
apolloFetchResponse = response;
next();
});
};
// Test for https://github.com/apollographql/apollo-server/issues/4170
it('works when using executeOperation', async () => {
const encounteredFields = [];
const encounteredContext = [];
await setupApolloServerAndFetchPairForPlugins([
{
requestDidStart: () => ({
executionDidStart: () => ({
willResolveField({ info, context }) {
encounteredFields.push(info.path);
encounteredContext.push(context);
},
}),
}),
},
]);
// The bug in 4170 (linked above) was occurring because of a failure
// to clone context in `executeOperation` in the same way that occurs
// in `runHttpQuery` prior to entering the request pipeline. That
// resulted in the inability to attach a symbol to the context because
// the symbol already existed on the context. Of course, a context
// is only created after the first invocation, so we'll run this twice
// to encounter the error where it was in the way when we tried to set
// it the second time. While we could have tested for the property
// before assigning to it, that is not the contract we have with the
// context, which should have been copied on `executeOperation` (which
// is meant to be used by testing, currently).
await serverInstance.executeOperation({
query: '{ justAField }',
});
await serverInstance.executeOperation({
query: '{ justAField }',
});
expect(encounteredFields).toStrictEqual([
{ key: 'justAField', prev: undefined },
{ key: 'justAField', prev: undefined },
]);
// This bit is just to ensure that nobody removes `context` from the
// `setupApolloServerAndFetchPairForPlugins` thinking it's unimportant.
// When a custom context is not provided, a new one is initialized
// on each request.
expect(encounteredContext).toStrictEqual([
expect.objectContaining({customContext: true}),
expect.objectContaining({customContext: true}),
]);
});
it('returns correct status code for a normal operation', async () => {
await setupApolloServerAndFetchPairForPlugins();
const result = await apolloFetch({ query: '{ justAField }' });
expect(result.errors).toBeUndefined();
expect(apolloFetchResponse.status).toEqual(200);
});
it('allows setting a custom status code for an error', async () => {
await setupApolloServerAndFetchPairForPlugins([
{
requestDidStart() {
return {
didResolveOperation() {
throw new Error('known_error');
},
willSendResponse({ response: { http, errors } }) {
if (errors[0].message === 'known_error') {
http.status = 403;
}
},
};
},
},
]);
const result = await apolloFetch({ query: '{ justAField }' });
expect(result.errors).toBeDefined();
expect(apolloFetchResponse.status).toEqual(403);
});
it('preserves user-added "extensions" in the response when parsing errors occur', async () => {
await setupApolloServerAndFetchPairForPlugins([
{
requestDidStart() {
return {
willSendResponse({ response }) {
response.extensions = { myExtension: true };
},
};
},
},
]);
const result =
await apolloFetch({ query: '{ 馃' });
expect(result.errors).toBeDefined();
expect(result.extensions).toEqual(expect.objectContaining({
myExtension: true
}));
});
it('preserves user-added "extensions" in the response when validation errors occur', async () => {
await setupApolloServerAndFetchPairForPlugins([
{
requestDidStart() {
return {
willSendResponse({ response }) {
response.extensions = { myExtension: true };
},
};
},
},
]);
const result =
await apolloFetch({ query: '{ missingFieldWhichWillNotValidate }' });
expect(result.errors).toBeDefined();
expect(result.extensions).toEqual(expect.objectContaining({
myExtension: true
}));
});
});
describe('formatError', () => {
it('wraps thrown error from validation rules', async () => {
const throwError = jest.fn(() => {
throw new Error('nope');
});
const formatError = jest.fn(error => {
expect(error instanceof Error).toBe(true);
expect(error.constructor.name).toEqual('Error');
return error;
});
const { url: uri } = await createApolloServer({
schema,
validationRules: [throwError],
introspection: true,
formatError,
});
const apolloFetch = createApolloFetch({ uri });
const introspectionResult = await apolloFetch({
query: INTROSPECTION_QUERY,
});
expect(introspectionResult.data).toBeUndefined();
expect(introspectionResult.errors).toBeDefined();
expect(formatError).toHaveBeenCalledTimes(1);
expect(throwError).toHaveBeenCalledTimes(1);
const result = await apolloFetch({ query: TEST_STRING_QUERY });
expect(result.data).toBeUndefined();
expect(result.errors).toBeDefined();
expect(formatError).toHaveBeenCalledTimes(2);
expect(throwError).toHaveBeenCalledTimes(2);
});
it('works with errors similar to GraphQL errors, such as yup', async () => {
// https://npm.im/yup is a package that produces a particular type of
// error that we test compatibility with. This test was first brought
// with https://github.com/apollographql/apollo-server/pull/1288. We
// used to use the actual `yup` package to generate the error, but we
// don't need to actually bundle that dependency just to test
// compatibility with that particular error shape. To be honest, it's
// not clear from the original PR which attribute of this error need be
// mocked, but for the sake not not breaking anything, all of yup's
// error properties have been reproduced here.
const throwError = jest.fn(async () => {
// Intentionally `any` because this is a custom Error class with
// various custom properties (like `value` and `params`).
const yuppieError: any = new Error('email must be a valid email');
yuppieError.name = 'ValidationError';
// Set `message` to enumerable, which `yup` does and `Error` doesn't.
Object.defineProperty(yuppieError, 'message', {
enumerable: true,
});
// Set other properties which `yup` sets.
yuppieError.path = 'email';
yuppieError.type = undefined;
yuppieError.value = { email: 'invalid-email' };
yuppieError.errors = ['email must be a valid email'];
yuppieError.inner = [];
yuppieError.params = {
path: 'email',
value: 'invalid-email',
originalValue: 'invalid-email',
label: undefined,
regex: /@/,
};
// This stack is fake, but roughly what `yup` generates!
yuppieError.stack = [
'ValidationError: email must be a valid email',
' at createError (yup/lib/util/createValidation.js:64:35)',
' at yup/lib/util/createValidation.js:113:108',
' at process._tickCallback (internal/process/next_tick.js:68:7)',
].join('\n');
throw yuppieError;
});
const formatError = jest.fn(error => {
expect(error instanceof Error).toBe(true);
expect(error.extensions.code).toEqual('INTERNAL_SERVER_ERROR');
expect(error.extensions.exception.name).toEqual('ValidationError');
expect(error.extensions.exception.message).toBeDefined();
const inputError = new UserInputError('User Input Error');
return {
message: inputError.message,
extensions: inputError.extensions,
};
});
const { url: uri } = await createApolloServer({
typeDefs: gql`
type Query {
fieldWhichWillError: String
}
`,
resolvers: {
Query: {
fieldWhichWillError: () => {
return throwError();
},
},
},
introspection: true,
debug: true,
formatError,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({
query: '{fieldWhichWillError}',
});
expect(result.data).toEqual({ fieldWhichWillError: null });
expect(result.errors).toBeDefined();
expect(result.errors[0].extensions.code).toEqual('BAD_USER_INPUT');
expect(result.errors[0].message).toEqual('User Input Error');
expect(formatError).toHaveBeenCalledTimes(1);
expect(throwError).toHaveBeenCalledTimes(1);
});
});
describe('lifecycle', () => {
describe('for Apollo usage reporting', () => {
let nodeEnv: string;
let reportIngress: MockReportIngress;
class MockReportIngress {
private app: express.Application;
private server: http.Server;
private reports: Report[] = [];
public readonly promiseOfReports: Promise<Report[]>;
constructor() {
let reportResolver: (reports: Report[]) => void;
this.promiseOfReports = new Promise<Report[]>(resolve => {
reportResolver = resolve;
});
this.app = express();
this.app.use((req, _res, next) => {
// body parser requires a content-type
req.headers['content-type'] = 'text/plain';
next();
});
this.app.use(
bodyParser.raw({
inflate: true,
type: '*/*',
}),
);
this.app.use((req, res) => {
const report = Report.decode(req.body);
this.reports.push(report);
res.end();
// Resolve any outstanding Promises with our new report data.
reportResolver(this.reports);
});
}
async listen(): Promise<http.Server> {
return await new Promise(resolve => {
const server = (this.server = this.app.listen(
0,
// Intentionally IPv4.
'127.0.0.1',
() => {
resolve(server);
},
));
});
}
async stop(): Promise<void> {
if (!this.server) {
return;
}
return new Promise(resolve => {
this.server && this.server.close(() => resolve());
});
}
getUrl(): string {
if (!this.server) {
throw new Error('must listen before getting URL');
}
const { family, address, port } = this.server.address();
if (family !== 'IPv4') {
throw new Error(`The family was unexpectedly ${family}.`);
}
return new URL(`http://${address}:${port}`).toString();
}
}
beforeEach(async () => {
nodeEnv = process.env.NODE_ENV;
delete process.env.NODE_ENV;
reportIngress = new MockReportIngress();
return await reportIngress.listen();
});
afterEach(done => {
process.env.NODE_ENV = nodeEnv;
(reportIngress.stop() || Promise.resolve()).then(done);
});
describe('extensions', () => {
// While it's been broken down quite a bit, this test is still
// overloaded and is a prime candidate for de-composition!
it('calls formatError and other overloaded client identity tests', async () => {
const throwError = jest.fn(() => {
throw new Error('nope');
});
const validationRule = jest.fn(() => {
// formatError should be called after validation
expect(formatError).not.toBeCalled();
// extension should be called after validation
expect(willSendResponseInExtension).not.toBeCalled();
return true;
});
const willSendResponseInExtension = jest.fn();
const formatError = jest.fn(error => {
try {
expect(error).toBeInstanceOf(Error);
// extension should be called before formatError