forked from mercurius-js/mercurius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.d.ts
718 lines (655 loc) · 21.4 KB
/
index.d.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
import {
FastifyError,
FastifyReply,
FastifyRequest,
FastifyInstance,
} from "fastify";
import {
DocumentNode,
ExecutionResult,
GraphQLSchema,
Source,
GraphQLResolveInfo,
GraphQLScalarType,
ValidationRule,
FormattedExecutionResult,
} from "graphql";
import { SocketStream } from "@fastify/websocket"
import { IncomingMessage, IncomingHttpHeaders, OutgoingHttpHeaders } from "http";
import { Readable } from "stream";
export interface PubSub {
subscribe<TResult = any>(topics: string | string[]): Promise<Readable & AsyncIterableIterator<TResult>>;
publish<TResult = any>(event: { topic: string; payload: TResult }, callback?: () => void): void;
}
export interface MercuriusContext {
app: FastifyInstance;
reply: FastifyReply;
operationsCount?: number;
operationId?: number;
__currentQuery: string;
/**
* __Caution__: Only available if `subscriptions` are enabled
*/
pubsub: PubSub;
}
export interface MercuriusError<TError extends Error = Error> extends FastifyError {
errors?: TError[]
}
export interface Loader<
TObj extends Record<string, any> = any,
TParams extends Record<string, any> = any,
TContext extends Record<string, any> = MercuriusContext
> {
(
queries: Array<{
obj: TObj;
params: TParams;
}>,
context: TContext & {
reply: FastifyReply;
}
): any;
}
export interface MercuriusLoaders<TContext extends Record<string, any> = MercuriusContext> {
[root: string]: {
[field: string]:
| Loader<any, any, TContext>
| {
loader: Loader<any, any, TContext>;
opts?: {
cache?: boolean;
};
};
};
}
// ------------------------
// Request Lifecycle hooks
// ------------------------
/**
* `preParsing` is the first hook to be executed in the GraphQL request lifecycle. The next hook will be `preValidation`.
*/
export interface preParsingHookHandler<TContext = MercuriusContext> {
(
schema: GraphQLSchema,
source: string,
context: TContext,
): Promise<void> | void;
}
/**
* `preValidation` is the second hook to be executed in the GraphQL request lifecycle. The previous hook was `preParsing`, the next hook will be `preExecution`.
*/
export interface preValidationHookHandler<TContext = MercuriusContext> {
(
schema: GraphQLSchema,
source: DocumentNode,
context: TContext,
): Promise<void> | void;
}
/**
* `preExecution` is the third hook to be executed in the GraphQL request lifecycle. The previous hook was `preValidation`.
* Notice: in the `preExecution` hook, you can modify the following items by returning them in the hook definition:
* - `schema`
* - `document`
* - `errors`
* - `variables`
*/
export interface preExecutionHookHandler<TContext = MercuriusContext, TError extends Error = Error> {
(
schema: GraphQLSchema,
source: DocumentNode,
context: TContext,
variables: Record<string, any>,
): Promise<PreExecutionHookResponse<TError> | void> | PreExecutionHookResponse<TError> | void;
}
/**
* `onResolution` is the fifth and final hook to be executed in the GraphQL request lifecycle. The previous hook was `preExecution`.
*/
export interface onResolutionHookHandler<TData extends Record<string, any> = Record<string, any>, TContext = MercuriusContext> {
(
execution: ExecutionResult<TData>,
context: TContext,
): Promise<void> | void;
}
// -----------------------------
// Subscription Lifecycle hooks
// -----------------------------
/**
* `preSubscriptionParsing` is the first hook to be executed in the GraphQL subscription lifecycle. The next hook will be `preSubscriptionExecution`.
* This hook will only be triggered when subscriptions are enabled.
*/
export interface preSubscriptionParsingHookHandler<TContext = MercuriusContext> {
(
schema: GraphQLSchema,
source: string,
context: TContext,
): Promise<void> | void;
}
/**
* `preSubscriptionExecution` is the second hook to be executed in the GraphQL subscription lifecycle. The previous hook was `preSubscriptionParsing`.
* This hook will only be triggered when subscriptions are enabled.
*/
export interface preSubscriptionExecutionHookHandler<TContext = MercuriusContext> {
(
schema: GraphQLSchema,
source: DocumentNode,
context: TContext,
): Promise<void> | void;
}
/**
* `onSubscriptionResolution` is the fourth hook to be executed in the GraphQL subscription lifecycle. The next hook will be `onSubscriptionEnd`.
* This hook will only be triggered when subscriptions are enabled.
*/
export interface onSubscriptionResolutionHookHandler<TData extends Record<string, any> = Record<string, any>, TContext = MercuriusContext> {
(
execution: ExecutionResult<TData>,
context: TContext,
): Promise<void> | void;
}
/**
* `onSubscriptionEnd` is the fifth and final hook to be executed in the GraphQL subscription lifecycle. The previous hook was `onSubscriptionResolution`.
* This hook will only be triggered when subscriptions are enabled.
*/
export interface onSubscriptionEndHookHandler<TContext = MercuriusContext> {
(
context: TContext,
id: string | number,
): Promise<void> | void;
}
// ----------------------------
// Application Lifecycle hooks
// ----------------------------
export interface onExtendSchemaHandler<TContext = MercuriusContext> {
(
schema: GraphQLSchema,
context: TContext,
): Promise<void> | void;
}
interface ServiceConfig {
setSchema: (schema: string) => ServiceConfig;
}
export interface MercuriusPlugin {
<
TData extends Record<string, any> = Record<string, any>,
TVariables extends Record<string, any> = Record<string, any>
>(
source: string,
context?: Record<string, any>,
variables?: TVariables,
operationName?: string
): Promise<ExecutionResult<TData>>;
/**
* Replace existing schema
* @param schema graphql schema
*/
replaceSchema(schema: GraphQLSchema): void;
/**
* Extend existing schema
* @param schema graphql schema
*/
extendSchema(schema: string | Source | DocumentNode): Promise<void> | void;
/**
* Define additional resolvers
* @param resolvers object with resolver functions
*/
defineResolvers<TContext extends Record<string, any> = MercuriusContext>(resolvers: IResolvers<any, TContext>): void;
/**
* Define data loaders
* @param loaders object with data loader functions
*/
defineLoaders<TContext extends Record<string, any> = MercuriusContext>(loaders: MercuriusLoaders<TContext>): void;
/**
* Transform the existing schema
*/
transformSchema: (
schemaTransforms:
| ((schema: GraphQLSchema) => GraphQLSchema)
| Array<(schema: GraphQLSchema) => GraphQLSchema>
) => void;
/**
* __Caution__: Only available if `subscriptions` are enabled
*/
pubsub: PubSub;
/**
* Managed GraphQL schema object for doing custom execution with. Will reflect changes made via `extendSchema`, `defineResolvers`, etc.
*/
schema: GraphQLSchema;
// addHook: overloads
// Request lifecycle addHooks
/**
* `preParsing` is the first hook to be executed in the GraphQL request lifecycle. The next hook will be `preValidation`.
*/
addHook<TContext = MercuriusContext>(name: 'preParsing', hook: preParsingHookHandler<TContext>): void;
/**
* `preValidation` is the second hook to be executed in the GraphQL request lifecycle. The previous hook was `preParsing`, the next hook will be `preExecution`.
*/
addHook<TContext = MercuriusContext>(name: 'preValidation', hook: preValidationHookHandler<TContext>): void;
/**
* `preExecution` is the third hook to be executed in the GraphQL request lifecycle. The previous hook was `preValidation`.
* Notice: in the `preExecution` hook, you can modify the following items by returning them in the hook definition:
* - `document`
* - `errors`
*/
addHook<TContext = MercuriusContext, TError extends Error = Error>(name: 'preExecution', hook: preExecutionHookHandler<TContext, TError>): void;
/**
* `onResolution` is the fifth and final hook to be executed in the GraphQL request lifecycle. The previous hook was `preExecution`.
*/
addHook<TData extends Record<string, any> = Record<string, any>, TContext = MercuriusContext>(name: 'onResolution', hook: onResolutionHookHandler<TData, TContext>): void;
// Subscription lifecycle addHooks
/**
* `preSubscriptionParsing` is the first hook to be executed in the GraphQL subscription lifecycle. The next hook will be `preSubscriptionExecution`.
* This hook will only be triggered when subscriptions are enabled.
*/
addHook<TContext = MercuriusContext>(name: 'preSubscriptionParsing', hook: preSubscriptionParsingHookHandler<TContext>): void;
/**
* `preSubscriptionExecution` is the second hook to be executed in the GraphQL subscription lifecycle. The previous hook was `preSubscriptionParsing`.
* This hook will only be triggered when subscriptions are enabled.
*/
addHook<TContext = MercuriusContext>(name: 'preSubscriptionExecution', hook: preSubscriptionExecutionHookHandler<TContext>): void;
/**
* `onSubscriptionResolution` is the fourth and final hook to be executed in the GraphQL subscription lifecycle.
* This hook will only be triggered when subscriptions are enabled.
*/
addHook<TData extends Record<string, any> = Record<string, any>, TContext = MercuriusContext>(name: 'onSubscriptionResolution', hook: onSubscriptionResolutionHookHandler<TData, TContext>): void;
/**
* `onSubscriptionEnd` is the fifth and final hook to be executed in the GraphQL subscription lifecycle. The previous hook was `onSubscriptionResolution`.
* This hook will only be triggered when subscriptions are enabled.
*/
addHook<TContext = MercuriusContext>(name: 'onSubscriptionEnd', hook: onSubscriptionEndHookHandler<TContext>): void;
// Application lifecycle addHooks
addHook<TContext = MercuriusContext>(name: 'onExtendSchema', hook: onExtendSchemaHandler<TContext>): void;
}
interface QueryRequest {
operationName?: string;
query: string;
variables?: object;
extensions?: object;
}
interface WsConnectionParams {
connectionInitPayload?:
| (() => Record<string, any> | Promise<Record<string, any>>)
| Record<string, any>;
reconnect?: boolean;
maxReconnectAttempts?: number;
connectionCallback?: () => void;
failedConnectionCallback?: (err: { message: string }) => void | Promise<void>;
failedReconnectCallback?: () => void;
rewriteConnectionInitPayload?: <TContext extends MercuriusContext = MercuriusContext>(payload: Record<string, any> | undefined, context: TContext) => Record<string, any>;
}
export interface MercuriusSchemaOptions {
/**
* The GraphQL schema. String schema will be parsed
*/
schema?: GraphQLSchema | string | string[];
/**
* Object with resolver functions
*/
resolvers?: IResolvers;
/**
* Object with data loader functions
*/
loaders?: MercuriusLoaders;
/**
* Schema transformation function or an array of schema transformation functions
*/
schemaTransforms?: ((originalSchema: GraphQLSchema) => GraphQLSchema) | Array<(originalSchema: GraphQLSchema) => GraphQLSchema>;
}
export interface MercuriusGraphiQLOptions {
/**
* Expose the graphiql app, default `true`
*/
enabled?: boolean;
/**
* The list of plugin to add to GraphiQL
*/
plugins?: Array<{
/**
* The name of the plugin, it should be the same exported in the `umd`
*/
name: string;
/**
* The props to be passed to the plugin
*/
props?: Object;
/**
* The urls of the plugin, it's downloaded at runtime. (eg. https://unpkg.com/myplugin/....)
*/
umdUrl: string;
/**
* A function name exported by the plugin to read/enrich the fetch response
*/
fetcherWrapper?: string;
}>
}
export interface MercuriusCommonOptions {
/**
* Serve GraphiQL on /graphiql if true or 'graphiql' and if routes is true
*/
graphiql?: boolean | 'graphiql' | MercuriusGraphiQLOptions;
ide?: boolean | 'graphiql' | MercuriusGraphiQLOptions;
/**
* The minimum number of execution a query needs to be executed before being jit'ed.
* @default 0 - disabled
*/
jit?: number;
/**
* A graphql endpoint is exposed at /graphql when true
* @default true
*/
routes?: boolean;
/**
* Define if the plugin can cache the responses.
* @default true
*/
cache?: boolean | number;
/**
* An endpoint for graphql if routes is true
* @default '/graphql'
*/
path?: string;
/**
* Change the route prefix of the graphql endpoint if set
*/
prefix?: string;
/**
* Add the empty Mutation definition if schema is not defined
* @default false
*/
defineMutation?: boolean;
/**
* Change the default error handler (Default: true).
* If a custom error handler is defined, it should send the standardized response format according to [GraphQL spec](https://graphql.org/learn/serving-over-http/#response) using `reply.send`.
* @default true
*/
errorHandler?:
| boolean
| ((error: MercuriusError, request: FastifyRequest, reply: FastifyReply) => void | Promise<void>);
/**
* Change the default error formatter.
*/
errorFormatter?: <TContext extends MercuriusContext = MercuriusContext>(
execution: ExecutionResult & Required<Pick<ExecutionResult, 'errors'>>,
context: TContext
) => {
statusCode: number;
response: ExecutionResult | FormattedExecutionResult;
};
/**
* The maximum depth allowed for a single query.
*/
queryDepth?: number;
context?: (
request: FastifyRequest,
reply: FastifyReply
) => Promise<Record<string, any>> | Record<string, any>;
/**
* Optional additional validation rules.
* Queries must satisfy these rules in addition to those defined by the GraphQL specification.
*/
validationRules?: ValidationRules;
/**
* Enable subscription support when options are provided. [`emitter`](https://github.com/mcollina/mqemitter) property is required when subscriptions is an object. (Default false)
*/
subscription?:
| boolean
| {
emitter?: object;
pubsub?: any; // FIXME: Technically this should be the PubSub type. But PubSub is now typed as SubscriptionContext.
verifyClient?: (
info: { origin: string; secure: boolean; req: IncomingMessage },
next: (
result: boolean,
code?: number,
message?: string,
headers?: OutgoingHttpHeaders
) => void
) => void;
context?: (
connection: SocketStream,
request: FastifyRequest
) => Record<string, any> | Promise<Record<string, any>>;
onConnect?: (data: {
type: 'connection_init';
payload: any;
}) => any;
onDisconnect?: (context: MercuriusContext) => void | Promise<void>;
keepAlive?: number,
fullWsTransport?: boolean,
};
/**
* Persisted queries, overrides persistedQueryProvider.
*/
persistedQueries?: Record<string,string>;
/**
* Only allow persisted queries. Required persistedQueries, overrides persistedQueryProvider.
*/
onlyPersisted?: boolean;
/**
* Settings for enabling persisted queries.
*/
persistedQueryProvider?: mercurius.PersistedQueryProvider;
/**
* Enable support for batched queries (POST requests only).
* Batched query support allows clients to send an array of queries and
* receive an array of responses within a single request.
*/
allowBatchedQueries?: boolean;
}
export type MercuriusOptions = MercuriusCommonOptions & (MercuriusSchemaOptions)
declare function mercurius
(
instance: FastifyInstance,
opts: MercuriusOptions
): void;
declare namespace mercurius {
interface PersistedQueryProvider {
/**
* Return true if a given request matches the desired persisted query format.
*/
isPersistedQuery: (r: QueryRequest) => boolean;
/**
* Return the hash from a given request, or falsy if this request format is not supported.
*/
getHash: (r: QueryRequest) => string;
/**
* Return the query for a given hash.
*/
getQueryFromHash: (hash: string) => Promise<string>;
/**
* Return the hash for a given query string. Do not provide if you want to skip saving new queries.
*/
getHashForQuery?: (query: string) => string;
/**
* Save a query, given its hash.
*/
saveQuery?: (hash: string, query: string) => Promise<void>;
/**
* An error message to return when getQueryFromHash returns a falsy result. Defaults to 'Bad Request'.
*/
notFoundError?: string;
/**
* An error message to return when a query matches isPersistedQuery, but fasly from getHash. Defaults to 'Bad Request'.
*/
notSupportedError?: string;
}
/**
* @deprecated Use `PersistedQueryProvider`
*/
interface PeristedQueryProvider extends PersistedQueryProvider {}
/**
* Extended errors for adding additional information in error responses
*/
class ErrorWithProps extends Error {
constructor(message: string, extensions?: object, statusCode?: number);
/**
* Custom additional properties of this error
*/
extensions?: object;
statusCode?: number;
}
/**
* Default options for persisted queries.
*/
const persistedQueryDefaults: {
prepared: (persistedQueries: object) => PersistedQueryProvider;
preparedOnly: (persistedQueries: object) => PersistedQueryProvider;
automatic: (maxSize?: number) => PersistedQueryProvider;
};
/**
* Default error formatter.
*/
const defaultErrorFormatter: (
execution: ExecutionResult & Required<Pick<ExecutionResult, 'errors'>>,
context: MercuriusContext
) => { statusCode: number; response: FormattedExecutionResult };
/**
* Subscriptions with filter functionality
*/
const withFilter: <
TPayload = any,
TSource = any,
TContext = MercuriusContext,
TArgs = Record<string, any>
>(
subscribeFn: IFieldResolver<TSource, TContext, TArgs>,
filterFn: (
payload: TPayload,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo & {
mergeInfo?: MergeInfo
}
) => boolean | Promise<boolean>
) => (
root: TSource,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo & {
mergeInfo?: MergeInfo
}
) => AsyncGenerator<TPayload>
}
export default mercurius;
declare module "fastify" {
interface FastifyInstance {
/**
* GraphQL plugin
*/
graphql: MercuriusPlugin;
}
interface FastifyReply {
/**
* @param source GraphQL query string
* @param context request context
* @param variables request variables which will get passed to the executor
* @param operationName specify which operation will be run
*/
graphql<
TData extends Record<string, any> = Record<string, any>,
TVariables extends Record<string, any> = Record<string, any>
>(
source: string,
context?: Record<string, any>,
variables?: TVariables,
operationName?: string
): Promise<ExecutionResult<TData>>;
}
}
export interface IResolvers<TSource = any, TContext = MercuriusContext> {
[key: string]:
| (() => any)
| IResolverObject<TSource, TContext>
| IResolverOptions<TSource, TContext>
| GraphQLScalarType
| IEnumResolver
| undefined;
}
export type IResolverObject<TSource = any, TContext = MercuriusContext, TArgs = any> = {
[key: string]:
| IFieldResolver<TSource, TContext, TArgs>
| IResolverOptions<TSource, TContext>
| IResolverObject<TSource, TContext>
| undefined;
}
export interface IResolverOptions<TSource = any, TContext = MercuriusContext, TArgs = any> {
fragment?: string;
resolve?: IFieldResolver<TSource, TContext, TArgs>;
subscribe?: IFieldResolver<TSource, TContext, TArgs>;
}
type IEnumResolver = {
[key: string]: string | number;
};
export interface IFieldResolver<TSource, TContext = MercuriusContext, TArgs = Record<string, any>> {
(
source: TSource,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo & {
mergeInfo?: MergeInfo;
}
): any;
}
type MergeInfo = {
delegate: (
type: "query" | "mutation" | "subscription",
fieldName: string,
args: {
[key: string]: any;
},
context: {
[key: string]: any;
},
info: GraphQLResolveInfo,
transforms?: Array<Transform>
) => any;
delegateToSchema<TContext>(options: IDelegateToSchemaOptions<TContext>): any;
fragments: Array<{
field: string;
fragment: string;
}>;
};
type Transform = {
transformSchema?: (schema: GraphQLSchema) => GraphQLSchema;
transformRequest?: (originalRequest: Request) => Request;
transformResult?: (result: Result) => Result;
};
interface IDelegateToSchemaOptions<
TContext = {
[key: string]: any;
}
> {
schema: GraphQLSchema;
operation: Operation;
fieldName: string;
args?: {
[key: string]: any;
};
context: TContext;
info: IGraphQLToolsResolveInfo;
transforms?: Array<Transform>;
skipValidation?: boolean;
}
type Operation = "query" | "mutation" | "subscription";
type Result = ExecutionResult & {
extensions?: Record<string, any>;
};
interface IGraphQLToolsResolveInfo extends GraphQLResolveInfo {
mergeInfo?: MergeInfo;
}
type Request = {
document: DocumentNode;
variables: Record<string, any>;
extensions?: Record<string, any>;
};
type ValidationRules =
| ValidationRule[]
| ((params: {
source: string;
variables?: Record<string, any>;
operationName?: string;
}) => ValidationRule[]);
export interface PreExecutionHookResponse<TError extends Error> {
schema?: GraphQLSchema
document?: DocumentNode
errors?: TError[],
variables?: Record<string, any>,
}