@graphql-hive/plugin-deduplicate-request 1.0.0-alpha-74133153a0ea2263e454190ec9e3c2326e553396

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @graphql-hive/plugin-deduplicate-request
2
+
3
+ ## 1.0.0-alpha-74133153a0ea2263e454190ec9e3c2326e553396
4
+
5
+ ### Major Changes
6
+
7
+ - [#1088](https://github.com/graphql-hive/gateway/pull/1088) [`2e02e54`](https://github.com/graphql-hive/gateway/commit/2e02e549bd5474a46917431707de5853a9ca9d64) Thanks [@enisdenjo](https://github.com/enisdenjo)! - Request deduplicate plugin for Hive Gateway
package/dist/index.cjs ADDED
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+
3
+ var utils = require('@graphql-mesh/utils');
4
+ var promiseHelpers = require('@whatwg-node/promise-helpers');
5
+
6
+ function useDeduplicateRequest() {
7
+ const reqResMapByContext = /* @__PURE__ */ new WeakMap();
8
+ function getReqResMapByContext(context) {
9
+ let reqResMap = reqResMapByContext.get(context);
10
+ if (!reqResMap) {
11
+ reqResMap = /* @__PURE__ */ new Map();
12
+ reqResMapByContext.set(context, reqResMap);
13
+ }
14
+ return reqResMap;
15
+ }
16
+ const resPropMap = /* @__PURE__ */ new WeakMap();
17
+ return {
18
+ onFetch({ url, options, context, info, fetchFn, setFetchFn, endResponse }) {
19
+ if (context != null) {
20
+ let method = "GET";
21
+ if (options.method) {
22
+ method = options.method;
23
+ }
24
+ if (method === "GET") {
25
+ const reqResMap = getReqResMapByContext(context);
26
+ let dedupCacheKey = url;
27
+ if (options.headers) {
28
+ const headersObj = utils.getHeadersObj(options.headers);
29
+ dedupCacheKey += JSON.stringify(headersObj);
30
+ }
31
+ const dedupRes$ = reqResMap.get(dedupCacheKey);
32
+ if (dedupRes$) {
33
+ endResponse(dedupRes$);
34
+ return;
35
+ }
36
+ setFetchFn(() => {
37
+ let dedupRes$2 = reqResMap.get(dedupCacheKey);
38
+ if (dedupRes$2 == null) {
39
+ dedupRes$2 = promiseHelpers.handleMaybePromise(
40
+ () => fetchFn(url, options, context, info),
41
+ (res) => {
42
+ let resPropMapByRes = resPropMap.get(res);
43
+ if (resPropMapByRes == null) {
44
+ resPropMapByRes = /* @__PURE__ */ new Map();
45
+ resPropMap.set(res, resPropMapByRes);
46
+ }
47
+ return new Proxy(res, {
48
+ get(target, prop) {
49
+ if (typeof target[prop] === "function") {
50
+ return (...args) => {
51
+ let resPropResult$ = resPropMapByRes.get(prop);
52
+ if (resPropResult$ == null) {
53
+ resPropResult$ = target[prop](...args);
54
+ resPropMapByRes.set(
55
+ prop,
56
+ // @ts-expect-error
57
+ resPropResult$
58
+ );
59
+ }
60
+ return resPropResult$;
61
+ };
62
+ }
63
+ return target[prop];
64
+ }
65
+ });
66
+ }
67
+ );
68
+ reqResMap.set(dedupCacheKey, dedupRes$2);
69
+ }
70
+ return dedupRes$2;
71
+ });
72
+ }
73
+ }
74
+ }
75
+ };
76
+ }
77
+
78
+ exports.useDeduplicateRequest = useDeduplicateRequest;
@@ -0,0 +1,308 @@
1
+ import { DisposableSymbols } from '@whatwg-node/disposablestack';
2
+ import { ExecutionRequest, ExecutionResult, Executor, MaybePromise as MaybePromise$1, Maybe } from '@graphql-tools/utils';
3
+ import { GraphQLSchema, OperationTypeNode, GraphQLFieldResolver, GraphQLResolveInfo, GraphQLOutputType, GraphQLError, SelectionSetNode, FragmentDefinitionNode, FieldNode, ExecutionResult as ExecutionResult$1, SelectionNode } from 'graphql';
4
+ import { Logger, MeshFetch, KeyValueCache, OnFetchHook } from '@graphql-mesh/types';
5
+ import DataLoader from 'dataloader';
6
+ import { GraphQLResolveInfo as GraphQLResolveInfo$1, GraphQLOutputType as GraphQLOutputType$1 } from 'graphql/type';
7
+ import { MaybePromise } from '@whatwg-node/promise-helpers';
8
+ import { Plugin, YogaInitialContext, Instrumentation as Instrumentation$2 } from 'graphql-yoga';
9
+ import { FetchInstrumentation } from '@graphql-mesh/utils';
10
+
11
+ type TopicDataMap = Record<string, any>;
12
+ interface HivePubSub<Data extends TopicDataMap = TopicDataMap> {
13
+ /** @deprecated Please use {@link subscribedTopics} if implemented instead. This method will be removed in next major release. */
14
+ getEventNames(): Iterable<keyof Data>;
15
+ /** @important This method will be required starting next major release. */
16
+ subscribedTopics?(): Iterable<keyof Data>;
17
+ publish<Topic extends keyof Data>(topic: Topic, data: Data[Topic]): void;
18
+ subscribe<Topic extends keyof Data>(topic: Topic, listener: PubSubListener<Data, Topic>): number;
19
+ unsubscribe(subId: number): void;
20
+ asyncIterator<Topic extends keyof Data>(topic: Topic): AsyncIterable<Data[Topic]>;
21
+ /** @important This method will be required starting next major release. */
22
+ dispose?(): void;
23
+ /** @important This method will be required starting next major release. */
24
+ [DisposableSymbols.dispose]?(): void;
25
+ }
26
+ type PubSubListener<Data extends TopicDataMap, Topic extends keyof Data> = (data: Data[Topic]) => void;
27
+
28
+ interface TransportEntry<Options extends Record<string, any> = Record<string, any>> {
29
+ kind: string;
30
+ subgraph: string;
31
+ location?: string;
32
+ headers?: [string, string][];
33
+ options?: Options;
34
+ }
35
+
36
+ type SchemaTransform<TContext = Record<any, string>> = (originalWrappingSchema: GraphQLSchema, subschemaConfig: SubschemaConfig<any, any, any, TContext>) => GraphQLSchema;
37
+ type RequestTransform<T = Record<string, any>, TContext = Record<any, string>> = (originalRequest: ExecutionRequest, delegationContext: DelegationContext<TContext>, transformationContext: T) => ExecutionRequest;
38
+ type ResultTransform<T = Record<string, any>, TContext = Record<any, string>> = (originalResult: ExecutionResult, delegationContext: DelegationContext<TContext>, transformationContext: T) => ExecutionResult;
39
+ interface Transform<T = any, TContext = Record<string, any>> {
40
+ transformSchema?: SchemaTransform<TContext>;
41
+ transformRequest?: RequestTransform<T, TContext>;
42
+ transformResult?: ResultTransform<T, TContext>;
43
+ }
44
+ interface DelegationContext<TContext = Record<string, any>> {
45
+ subschema: GraphQLSchema | SubschemaConfig<any, any, any, TContext>;
46
+ subschemaConfig?: SubschemaConfig<any, any, any, TContext>;
47
+ targetSchema: GraphQLSchema;
48
+ operation: OperationTypeNode;
49
+ fieldName: string;
50
+ args?: Record<string, any>;
51
+ context?: TContext;
52
+ info?: GraphQLResolveInfo;
53
+ returnType: GraphQLOutputType;
54
+ onLocatedError?: (originalError: GraphQLError) => GraphQLError;
55
+ rootValue?: any;
56
+ transforms: Array<Transform<any, TContext>>;
57
+ transformedSchema: GraphQLSchema;
58
+ skipTypeMerging: boolean;
59
+ }
60
+ type DelegationPlanBuilder = (schema: GraphQLSchema, sourceSubschema: Subschema<any, any, any, any>, variableValues: Record<string, any>, fragments: Record<string, FragmentDefinitionNode>, fieldNodes: FieldNode[], context?: any, info?: GraphQLResolveInfo) => Array<Map<Subschema, SelectionSetNode>>;
61
+ interface ICreateProxyingResolverOptions<TContext = Record<string, any>> {
62
+ subschemaConfig: SubschemaConfig<any, any, any, TContext>;
63
+ operation?: OperationTypeNode;
64
+ fieldName?: string;
65
+ }
66
+ type CreateProxyingResolverFn<TContext = Record<string, any>> = (options: ICreateProxyingResolverOptions<TContext>) => GraphQLFieldResolver<any, TContext>;
67
+ interface BatchingOptions<K = any, V = any, C = K> {
68
+ extensionsReducer?: (mergedExtensions: Record<string, any>, request: ExecutionRequest) => Record<string, any>;
69
+ dataLoaderOptions?: DataLoader.Options<K, V, C>;
70
+ }
71
+ interface SubschemaConfig<K = any, V = any, C = K, TContext = Record<string, any>> {
72
+ name?: string;
73
+ schema: GraphQLSchema;
74
+ createProxyingResolver?: CreateProxyingResolverFn<TContext>;
75
+ rootValue?: any;
76
+ transforms?: Array<Transform<any, TContext>>;
77
+ merge?: Record<string, MergedTypeConfig<any, any, TContext>>;
78
+ executor?: Executor<TContext>;
79
+ batch?: boolean;
80
+ batchingOptions?: BatchingOptions<K, V, C>;
81
+ }
82
+ interface MergedTypeConfig<K = any, V = any, TContext = Record<string, any>> extends MergedTypeEntryPoint<K, V, TContext> {
83
+ entryPoints?: Array<MergedTypeEntryPoint>;
84
+ fields?: Record<string, MergedFieldConfig>;
85
+ canonical?: boolean;
86
+ }
87
+ interface MergedTypeEntryPoint<K = any, V = any, TContext = Record<string, any>> extends MergedTypeResolverOptions<K, V> {
88
+ selectionSet?: string;
89
+ key?: (originalResult: any) => K | PromiseLike<K>;
90
+ resolve?: MergedTypeResolver<TContext>;
91
+ }
92
+ interface MergedTypeResolverOptions<K = any, V = any> {
93
+ fieldName?: string;
94
+ args?: (originalResult: any) => Record<string, any>;
95
+ argsFromKeys?: (keys: ReadonlyArray<K>) => Record<string, any>;
96
+ valuesFromResults?: (results: any, keys: ReadonlyArray<K>) => Array<V>;
97
+ dataLoaderOptions?: DataLoader.Options<K, V>;
98
+ }
99
+ interface MergedFieldConfig {
100
+ selectionSet?: string;
101
+ computed?: boolean;
102
+ canonical?: boolean;
103
+ provides?: SelectionSetNode;
104
+ }
105
+ type MergedTypeResolver<TContext = Record<string, any>> = (originalResult: any, context: TContext, info: GraphQLResolveInfo, subschema: Subschema<any, any, any, TContext>, selectionSet: SelectionSetNode, key: any | undefined, type: GraphQLOutputType) => any;
106
+
107
+ interface ISubschema<K = any, V = any, C = K, TContext = Record<string, any>> extends SubschemaConfig<K, V, C, TContext> {
108
+ transformedSchema: GraphQLSchema;
109
+ }
110
+ declare class Subschema<K = any, V = any, C = K, TContext = Record<string, any>> implements ISubschema<K, V, C, TContext> {
111
+ name?: string;
112
+ schema: GraphQLSchema;
113
+ executor?: Executor<TContext>;
114
+ batch?: boolean;
115
+ batchingOptions?: BatchingOptions<K, V, C>;
116
+ createProxyingResolver?: CreateProxyingResolverFn<TContext>;
117
+ transforms: Array<Transform<any, TContext>>;
118
+ private _transformedSchema;
119
+ merge?: Record<string, MergedTypeConfig<any, any, TContext>>;
120
+ constructor(config: SubschemaConfig<K, V, C, TContext>);
121
+ get transformedSchema(): GraphQLSchema;
122
+ set transformedSchema(value: GraphQLSchema);
123
+ }
124
+
125
+ type Instrumentation$1 = {
126
+ /**
127
+ * Wrap each subgraph execution request. This can happen multiple time for the same graphql operation.
128
+ */
129
+ subgraphExecute?: (payload: {
130
+ executionRequest: ExecutionRequest;
131
+ }, wrapped: () => MaybePromise<void>) => MaybePromise<void>;
132
+ };
133
+
134
+ declare module 'graphql' {
135
+ interface GraphQLResolveInfo {
136
+ executionRequest?: ExecutionRequest;
137
+ }
138
+ }
139
+ interface UnifiedGraphPlugin<TContext> {
140
+ onSubgraphExecute?: OnSubgraphExecuteHook<TContext>;
141
+ onDelegationPlan?: OnDelegationPlanHook<TContext>;
142
+ onDelegationStageExecute?: OnDelegationStageExecuteHook<TContext>;
143
+ }
144
+ type OnSubgraphExecuteHook<TContext = any> = (payload: OnSubgraphExecutePayload<TContext>) => MaybePromise$1<Maybe<OnSubgraphExecuteDoneHook | void>>;
145
+ interface OnSubgraphExecutePayload<TContext> {
146
+ subgraph: GraphQLSchema;
147
+ subgraphName: string;
148
+ transportEntry?: TransportEntry;
149
+ executionRequest: ExecutionRequest<any, TContext>;
150
+ setExecutionRequest(executionRequest: ExecutionRequest): void;
151
+ executor: Executor;
152
+ setExecutor(executor: Executor): void;
153
+ requestId?: string;
154
+ logger?: Logger;
155
+ }
156
+ interface OnSubgraphExecuteDonePayload {
157
+ result: AsyncIterable<ExecutionResult$1> | ExecutionResult$1;
158
+ setResult(result: AsyncIterable<ExecutionResult$1> | ExecutionResult$1): void;
159
+ }
160
+ type OnSubgraphExecuteDoneHook = (payload: OnSubgraphExecuteDonePayload) => MaybePromise$1<Maybe<OnSubgraphExecuteDoneResult | void>>;
161
+ type OnSubgraphExecuteDoneResultOnNext = (payload: OnSubgraphExecuteDoneOnNextPayload) => MaybePromise$1<void>;
162
+ interface OnSubgraphExecuteDoneOnNextPayload {
163
+ result: ExecutionResult$1;
164
+ setResult(result: ExecutionResult$1): void;
165
+ }
166
+ type OnSubgraphExecuteDoneResultOnEnd = () => MaybePromise$1<void>;
167
+ type OnSubgraphExecuteDoneResult = {
168
+ onNext?: OnSubgraphExecuteDoneResultOnNext;
169
+ onEnd?: OnSubgraphExecuteDoneResultOnEnd;
170
+ };
171
+ type OnDelegationPlanHook<TContext> = (payload: OnDelegationPlanHookPayload<TContext>) => Maybe<OnDelegationPlanDoneHook | void>;
172
+ interface OnDelegationPlanHookPayload<TContext> {
173
+ supergraph: GraphQLSchema;
174
+ subgraph: string;
175
+ sourceSubschema: Subschema<any, any, any, TContext>;
176
+ typeName: string;
177
+ variables: Record<string, any>;
178
+ fragments: Record<string, FragmentDefinitionNode>;
179
+ fieldNodes: SelectionNode[];
180
+ context: TContext;
181
+ requestId?: string;
182
+ logger?: Logger;
183
+ info?: GraphQLResolveInfo$1;
184
+ delegationPlanBuilder: DelegationPlanBuilder;
185
+ setDelegationPlanBuilder(delegationPlanBuilder: DelegationPlanBuilder): void;
186
+ }
187
+ type OnDelegationPlanDoneHook = (payload: OnDelegationPlanDonePayload) => Maybe<void>;
188
+ interface OnDelegationPlanDonePayload {
189
+ delegationPlan: ReturnType<DelegationPlanBuilder>;
190
+ setDelegationPlan: (delegationPlan: ReturnType<DelegationPlanBuilder>) => void;
191
+ }
192
+ type OnDelegationStageExecuteHook<TContext> = (payload: OnDelegationStageExecutePayload<TContext>) => Maybe<OnDelegationStageExecuteDoneHook>;
193
+ interface OnDelegationStageExecutePayload<TContext> {
194
+ object: any;
195
+ context: TContext;
196
+ info: GraphQLResolveInfo$1;
197
+ subgraph: string;
198
+ subschema: Subschema<any, any, any, TContext>;
199
+ selectionSet: SelectionSetNode;
200
+ key?: any;
201
+ type: GraphQLOutputType$1;
202
+ resolver: MergedTypeResolver<TContext>;
203
+ setResolver: (resolver: MergedTypeResolver<TContext>) => void;
204
+ typeName: string;
205
+ requestId?: string;
206
+ logger?: Logger;
207
+ }
208
+ type OnDelegationStageExecuteDoneHook = (payload: OnDelegationStageExecuteDonePayload) => void;
209
+ interface OnDelegationStageExecuteDonePayload {
210
+ result: any;
211
+ setResult: (result: any) => void;
212
+ }
213
+
214
+ interface GatewayConfigContext {
215
+ /**
216
+ * WHATWG compatible Fetch implementation.
217
+ */
218
+ fetch: MeshFetch;
219
+ /**
220
+ * The logger to use throught Mesh and it's plugins.
221
+ */
222
+ logger: Logger;
223
+ /**
224
+ * Current working directory.
225
+ */
226
+ cwd: string;
227
+ /**
228
+ * Event bus for pub/sub.
229
+ */
230
+ pubsub?: HivePubSub;
231
+ /**
232
+ * Cache Storage
233
+ */
234
+ cache?: KeyValueCache;
235
+ }
236
+ interface GatewayContext extends GatewayConfigContext, YogaInitialContext {
237
+ /**
238
+ * Environment agnostic HTTP headers provided with the request.
239
+ */
240
+ headers: Record<string, string>;
241
+ /**
242
+ * Runtime context available within WebSocket connections.
243
+ */
244
+ connectionParams: Record<string, string>;
245
+ }
246
+ type GatewayPlugin<TPluginContext extends Record<string, any> = Record<string, any>, TContext extends Record<string, any> = Record<string, any>> = Plugin<Partial<TPluginContext> & GatewayContext & TContext> & UnifiedGraphPlugin<Partial<TPluginContext> & GatewayContext & TContext> & {
247
+ onFetch?: OnFetchHook<Partial<TPluginContext> & GatewayContext & TContext>;
248
+ onCacheGet?: OnCacheGetHook;
249
+ onCacheSet?: OnCacheSetHook;
250
+ onCacheDelete?: OnCacheDeleteHook;
251
+ /**
252
+ * An Instrumentation instance that will wrap each phases of the request pipeline.
253
+ * This should be used primarily as an observability tool (for monitoring, tracing, etc...).
254
+ *
255
+ * Note: The wrapped functions in instrumentation should always be called. Use hooks to
256
+ * conditionally skip a phase.
257
+ */
258
+ instrumentation?: Instrumentation<TPluginContext & TContext & GatewayContext>;
259
+ };
260
+ type OnCacheGetHook = (payload: OnCacheGetHookEventPayload) => MaybePromise$1<OnCacheGetHookResult | void>;
261
+ interface OnCacheGetHookEventPayload {
262
+ cache: KeyValueCache;
263
+ key: string;
264
+ ttl?: number;
265
+ }
266
+ interface OnCacheGetHookResult {
267
+ onCacheHit?: OnCacheHitHook;
268
+ onCacheMiss?: OnCacheMissHook;
269
+ onCacheGetError?: OnCacheErrorHook;
270
+ }
271
+ type OnCacheErrorHook = (payload: OnCacheErrorHookPayload) => void;
272
+ interface OnCacheErrorHookPayload {
273
+ error: Error;
274
+ }
275
+ type OnCacheHitHook = (payload: OnCacheHitHookEventPayload) => void;
276
+ interface OnCacheHitHookEventPayload {
277
+ value: any;
278
+ }
279
+ type OnCacheMissHook = () => void;
280
+ type OnCacheSetHook = (payload: OnCacheSetHookEventPayload) => MaybePromise$1<OnCacheSetHookResult | void>;
281
+ interface OnCacheSetHookResult {
282
+ onCacheSetDone?: () => void;
283
+ onCacheSetError?: OnCacheErrorHook;
284
+ }
285
+ interface OnCacheSetHookEventPayload {
286
+ cache: KeyValueCache;
287
+ key: string;
288
+ value: any;
289
+ ttl?: number;
290
+ }
291
+ type OnCacheDeleteHook = (payload: OnCacheDeleteHookEventPayload) => MaybePromise$1<OnCacheDeleteHookResult | void>;
292
+ interface OnCacheDeleteHookResult {
293
+ onCacheDeleteDone?: () => void;
294
+ onCacheDeleteError?: OnCacheErrorHook;
295
+ }
296
+ interface OnCacheDeleteHookEventPayload {
297
+ cache: KeyValueCache;
298
+ key: string;
299
+ }
300
+ type Instrumentation<TContext extends Record<string, any>> = Instrumentation$2<TContext> & Instrumentation$1 & FetchInstrumentation;
301
+
302
+ declare global {
303
+ var DEBUG: string;
304
+ }
305
+
306
+ declare function useDeduplicateRequest(): GatewayPlugin;
307
+
308
+ export { useDeduplicateRequest };
@@ -0,0 +1,308 @@
1
+ import { DisposableSymbols } from '@whatwg-node/disposablestack';
2
+ import { ExecutionRequest, ExecutionResult, Executor, MaybePromise as MaybePromise$1, Maybe } from '@graphql-tools/utils';
3
+ import { GraphQLSchema, OperationTypeNode, GraphQLFieldResolver, GraphQLResolveInfo, GraphQLOutputType, GraphQLError, SelectionSetNode, FragmentDefinitionNode, FieldNode, ExecutionResult as ExecutionResult$1, SelectionNode } from 'graphql';
4
+ import { Logger, MeshFetch, KeyValueCache, OnFetchHook } from '@graphql-mesh/types';
5
+ import DataLoader from 'dataloader';
6
+ import { GraphQLResolveInfo as GraphQLResolveInfo$1, GraphQLOutputType as GraphQLOutputType$1 } from 'graphql/type';
7
+ import { MaybePromise } from '@whatwg-node/promise-helpers';
8
+ import { Plugin, YogaInitialContext, Instrumentation as Instrumentation$2 } from 'graphql-yoga';
9
+ import { FetchInstrumentation } from '@graphql-mesh/utils';
10
+
11
+ type TopicDataMap = Record<string, any>;
12
+ interface HivePubSub<Data extends TopicDataMap = TopicDataMap> {
13
+ /** @deprecated Please use {@link subscribedTopics} if implemented instead. This method will be removed in next major release. */
14
+ getEventNames(): Iterable<keyof Data>;
15
+ /** @important This method will be required starting next major release. */
16
+ subscribedTopics?(): Iterable<keyof Data>;
17
+ publish<Topic extends keyof Data>(topic: Topic, data: Data[Topic]): void;
18
+ subscribe<Topic extends keyof Data>(topic: Topic, listener: PubSubListener<Data, Topic>): number;
19
+ unsubscribe(subId: number): void;
20
+ asyncIterator<Topic extends keyof Data>(topic: Topic): AsyncIterable<Data[Topic]>;
21
+ /** @important This method will be required starting next major release. */
22
+ dispose?(): void;
23
+ /** @important This method will be required starting next major release. */
24
+ [DisposableSymbols.dispose]?(): void;
25
+ }
26
+ type PubSubListener<Data extends TopicDataMap, Topic extends keyof Data> = (data: Data[Topic]) => void;
27
+
28
+ interface TransportEntry<Options extends Record<string, any> = Record<string, any>> {
29
+ kind: string;
30
+ subgraph: string;
31
+ location?: string;
32
+ headers?: [string, string][];
33
+ options?: Options;
34
+ }
35
+
36
+ type SchemaTransform<TContext = Record<any, string>> = (originalWrappingSchema: GraphQLSchema, subschemaConfig: SubschemaConfig<any, any, any, TContext>) => GraphQLSchema;
37
+ type RequestTransform<T = Record<string, any>, TContext = Record<any, string>> = (originalRequest: ExecutionRequest, delegationContext: DelegationContext<TContext>, transformationContext: T) => ExecutionRequest;
38
+ type ResultTransform<T = Record<string, any>, TContext = Record<any, string>> = (originalResult: ExecutionResult, delegationContext: DelegationContext<TContext>, transformationContext: T) => ExecutionResult;
39
+ interface Transform<T = any, TContext = Record<string, any>> {
40
+ transformSchema?: SchemaTransform<TContext>;
41
+ transformRequest?: RequestTransform<T, TContext>;
42
+ transformResult?: ResultTransform<T, TContext>;
43
+ }
44
+ interface DelegationContext<TContext = Record<string, any>> {
45
+ subschema: GraphQLSchema | SubschemaConfig<any, any, any, TContext>;
46
+ subschemaConfig?: SubschemaConfig<any, any, any, TContext>;
47
+ targetSchema: GraphQLSchema;
48
+ operation: OperationTypeNode;
49
+ fieldName: string;
50
+ args?: Record<string, any>;
51
+ context?: TContext;
52
+ info?: GraphQLResolveInfo;
53
+ returnType: GraphQLOutputType;
54
+ onLocatedError?: (originalError: GraphQLError) => GraphQLError;
55
+ rootValue?: any;
56
+ transforms: Array<Transform<any, TContext>>;
57
+ transformedSchema: GraphQLSchema;
58
+ skipTypeMerging: boolean;
59
+ }
60
+ type DelegationPlanBuilder = (schema: GraphQLSchema, sourceSubschema: Subschema<any, any, any, any>, variableValues: Record<string, any>, fragments: Record<string, FragmentDefinitionNode>, fieldNodes: FieldNode[], context?: any, info?: GraphQLResolveInfo) => Array<Map<Subschema, SelectionSetNode>>;
61
+ interface ICreateProxyingResolverOptions<TContext = Record<string, any>> {
62
+ subschemaConfig: SubschemaConfig<any, any, any, TContext>;
63
+ operation?: OperationTypeNode;
64
+ fieldName?: string;
65
+ }
66
+ type CreateProxyingResolverFn<TContext = Record<string, any>> = (options: ICreateProxyingResolverOptions<TContext>) => GraphQLFieldResolver<any, TContext>;
67
+ interface BatchingOptions<K = any, V = any, C = K> {
68
+ extensionsReducer?: (mergedExtensions: Record<string, any>, request: ExecutionRequest) => Record<string, any>;
69
+ dataLoaderOptions?: DataLoader.Options<K, V, C>;
70
+ }
71
+ interface SubschemaConfig<K = any, V = any, C = K, TContext = Record<string, any>> {
72
+ name?: string;
73
+ schema: GraphQLSchema;
74
+ createProxyingResolver?: CreateProxyingResolverFn<TContext>;
75
+ rootValue?: any;
76
+ transforms?: Array<Transform<any, TContext>>;
77
+ merge?: Record<string, MergedTypeConfig<any, any, TContext>>;
78
+ executor?: Executor<TContext>;
79
+ batch?: boolean;
80
+ batchingOptions?: BatchingOptions<K, V, C>;
81
+ }
82
+ interface MergedTypeConfig<K = any, V = any, TContext = Record<string, any>> extends MergedTypeEntryPoint<K, V, TContext> {
83
+ entryPoints?: Array<MergedTypeEntryPoint>;
84
+ fields?: Record<string, MergedFieldConfig>;
85
+ canonical?: boolean;
86
+ }
87
+ interface MergedTypeEntryPoint<K = any, V = any, TContext = Record<string, any>> extends MergedTypeResolverOptions<K, V> {
88
+ selectionSet?: string;
89
+ key?: (originalResult: any) => K | PromiseLike<K>;
90
+ resolve?: MergedTypeResolver<TContext>;
91
+ }
92
+ interface MergedTypeResolverOptions<K = any, V = any> {
93
+ fieldName?: string;
94
+ args?: (originalResult: any) => Record<string, any>;
95
+ argsFromKeys?: (keys: ReadonlyArray<K>) => Record<string, any>;
96
+ valuesFromResults?: (results: any, keys: ReadonlyArray<K>) => Array<V>;
97
+ dataLoaderOptions?: DataLoader.Options<K, V>;
98
+ }
99
+ interface MergedFieldConfig {
100
+ selectionSet?: string;
101
+ computed?: boolean;
102
+ canonical?: boolean;
103
+ provides?: SelectionSetNode;
104
+ }
105
+ type MergedTypeResolver<TContext = Record<string, any>> = (originalResult: any, context: TContext, info: GraphQLResolveInfo, subschema: Subschema<any, any, any, TContext>, selectionSet: SelectionSetNode, key: any | undefined, type: GraphQLOutputType) => any;
106
+
107
+ interface ISubschema<K = any, V = any, C = K, TContext = Record<string, any>> extends SubschemaConfig<K, V, C, TContext> {
108
+ transformedSchema: GraphQLSchema;
109
+ }
110
+ declare class Subschema<K = any, V = any, C = K, TContext = Record<string, any>> implements ISubschema<K, V, C, TContext> {
111
+ name?: string;
112
+ schema: GraphQLSchema;
113
+ executor?: Executor<TContext>;
114
+ batch?: boolean;
115
+ batchingOptions?: BatchingOptions<K, V, C>;
116
+ createProxyingResolver?: CreateProxyingResolverFn<TContext>;
117
+ transforms: Array<Transform<any, TContext>>;
118
+ private _transformedSchema;
119
+ merge?: Record<string, MergedTypeConfig<any, any, TContext>>;
120
+ constructor(config: SubschemaConfig<K, V, C, TContext>);
121
+ get transformedSchema(): GraphQLSchema;
122
+ set transformedSchema(value: GraphQLSchema);
123
+ }
124
+
125
+ type Instrumentation$1 = {
126
+ /**
127
+ * Wrap each subgraph execution request. This can happen multiple time for the same graphql operation.
128
+ */
129
+ subgraphExecute?: (payload: {
130
+ executionRequest: ExecutionRequest;
131
+ }, wrapped: () => MaybePromise<void>) => MaybePromise<void>;
132
+ };
133
+
134
+ declare module 'graphql' {
135
+ interface GraphQLResolveInfo {
136
+ executionRequest?: ExecutionRequest;
137
+ }
138
+ }
139
+ interface UnifiedGraphPlugin<TContext> {
140
+ onSubgraphExecute?: OnSubgraphExecuteHook<TContext>;
141
+ onDelegationPlan?: OnDelegationPlanHook<TContext>;
142
+ onDelegationStageExecute?: OnDelegationStageExecuteHook<TContext>;
143
+ }
144
+ type OnSubgraphExecuteHook<TContext = any> = (payload: OnSubgraphExecutePayload<TContext>) => MaybePromise$1<Maybe<OnSubgraphExecuteDoneHook | void>>;
145
+ interface OnSubgraphExecutePayload<TContext> {
146
+ subgraph: GraphQLSchema;
147
+ subgraphName: string;
148
+ transportEntry?: TransportEntry;
149
+ executionRequest: ExecutionRequest<any, TContext>;
150
+ setExecutionRequest(executionRequest: ExecutionRequest): void;
151
+ executor: Executor;
152
+ setExecutor(executor: Executor): void;
153
+ requestId?: string;
154
+ logger?: Logger;
155
+ }
156
+ interface OnSubgraphExecuteDonePayload {
157
+ result: AsyncIterable<ExecutionResult$1> | ExecutionResult$1;
158
+ setResult(result: AsyncIterable<ExecutionResult$1> | ExecutionResult$1): void;
159
+ }
160
+ type OnSubgraphExecuteDoneHook = (payload: OnSubgraphExecuteDonePayload) => MaybePromise$1<Maybe<OnSubgraphExecuteDoneResult | void>>;
161
+ type OnSubgraphExecuteDoneResultOnNext = (payload: OnSubgraphExecuteDoneOnNextPayload) => MaybePromise$1<void>;
162
+ interface OnSubgraphExecuteDoneOnNextPayload {
163
+ result: ExecutionResult$1;
164
+ setResult(result: ExecutionResult$1): void;
165
+ }
166
+ type OnSubgraphExecuteDoneResultOnEnd = () => MaybePromise$1<void>;
167
+ type OnSubgraphExecuteDoneResult = {
168
+ onNext?: OnSubgraphExecuteDoneResultOnNext;
169
+ onEnd?: OnSubgraphExecuteDoneResultOnEnd;
170
+ };
171
+ type OnDelegationPlanHook<TContext> = (payload: OnDelegationPlanHookPayload<TContext>) => Maybe<OnDelegationPlanDoneHook | void>;
172
+ interface OnDelegationPlanHookPayload<TContext> {
173
+ supergraph: GraphQLSchema;
174
+ subgraph: string;
175
+ sourceSubschema: Subschema<any, any, any, TContext>;
176
+ typeName: string;
177
+ variables: Record<string, any>;
178
+ fragments: Record<string, FragmentDefinitionNode>;
179
+ fieldNodes: SelectionNode[];
180
+ context: TContext;
181
+ requestId?: string;
182
+ logger?: Logger;
183
+ info?: GraphQLResolveInfo$1;
184
+ delegationPlanBuilder: DelegationPlanBuilder;
185
+ setDelegationPlanBuilder(delegationPlanBuilder: DelegationPlanBuilder): void;
186
+ }
187
+ type OnDelegationPlanDoneHook = (payload: OnDelegationPlanDonePayload) => Maybe<void>;
188
+ interface OnDelegationPlanDonePayload {
189
+ delegationPlan: ReturnType<DelegationPlanBuilder>;
190
+ setDelegationPlan: (delegationPlan: ReturnType<DelegationPlanBuilder>) => void;
191
+ }
192
+ type OnDelegationStageExecuteHook<TContext> = (payload: OnDelegationStageExecutePayload<TContext>) => Maybe<OnDelegationStageExecuteDoneHook>;
193
+ interface OnDelegationStageExecutePayload<TContext> {
194
+ object: any;
195
+ context: TContext;
196
+ info: GraphQLResolveInfo$1;
197
+ subgraph: string;
198
+ subschema: Subschema<any, any, any, TContext>;
199
+ selectionSet: SelectionSetNode;
200
+ key?: any;
201
+ type: GraphQLOutputType$1;
202
+ resolver: MergedTypeResolver<TContext>;
203
+ setResolver: (resolver: MergedTypeResolver<TContext>) => void;
204
+ typeName: string;
205
+ requestId?: string;
206
+ logger?: Logger;
207
+ }
208
+ type OnDelegationStageExecuteDoneHook = (payload: OnDelegationStageExecuteDonePayload) => void;
209
+ interface OnDelegationStageExecuteDonePayload {
210
+ result: any;
211
+ setResult: (result: any) => void;
212
+ }
213
+
214
+ interface GatewayConfigContext {
215
+ /**
216
+ * WHATWG compatible Fetch implementation.
217
+ */
218
+ fetch: MeshFetch;
219
+ /**
220
+ * The logger to use throught Mesh and it's plugins.
221
+ */
222
+ logger: Logger;
223
+ /**
224
+ * Current working directory.
225
+ */
226
+ cwd: string;
227
+ /**
228
+ * Event bus for pub/sub.
229
+ */
230
+ pubsub?: HivePubSub;
231
+ /**
232
+ * Cache Storage
233
+ */
234
+ cache?: KeyValueCache;
235
+ }
236
+ interface GatewayContext extends GatewayConfigContext, YogaInitialContext {
237
+ /**
238
+ * Environment agnostic HTTP headers provided with the request.
239
+ */
240
+ headers: Record<string, string>;
241
+ /**
242
+ * Runtime context available within WebSocket connections.
243
+ */
244
+ connectionParams: Record<string, string>;
245
+ }
246
+ type GatewayPlugin<TPluginContext extends Record<string, any> = Record<string, any>, TContext extends Record<string, any> = Record<string, any>> = Plugin<Partial<TPluginContext> & GatewayContext & TContext> & UnifiedGraphPlugin<Partial<TPluginContext> & GatewayContext & TContext> & {
247
+ onFetch?: OnFetchHook<Partial<TPluginContext> & GatewayContext & TContext>;
248
+ onCacheGet?: OnCacheGetHook;
249
+ onCacheSet?: OnCacheSetHook;
250
+ onCacheDelete?: OnCacheDeleteHook;
251
+ /**
252
+ * An Instrumentation instance that will wrap each phases of the request pipeline.
253
+ * This should be used primarily as an observability tool (for monitoring, tracing, etc...).
254
+ *
255
+ * Note: The wrapped functions in instrumentation should always be called. Use hooks to
256
+ * conditionally skip a phase.
257
+ */
258
+ instrumentation?: Instrumentation<TPluginContext & TContext & GatewayContext>;
259
+ };
260
+ type OnCacheGetHook = (payload: OnCacheGetHookEventPayload) => MaybePromise$1<OnCacheGetHookResult | void>;
261
+ interface OnCacheGetHookEventPayload {
262
+ cache: KeyValueCache;
263
+ key: string;
264
+ ttl?: number;
265
+ }
266
+ interface OnCacheGetHookResult {
267
+ onCacheHit?: OnCacheHitHook;
268
+ onCacheMiss?: OnCacheMissHook;
269
+ onCacheGetError?: OnCacheErrorHook;
270
+ }
271
+ type OnCacheErrorHook = (payload: OnCacheErrorHookPayload) => void;
272
+ interface OnCacheErrorHookPayload {
273
+ error: Error;
274
+ }
275
+ type OnCacheHitHook = (payload: OnCacheHitHookEventPayload) => void;
276
+ interface OnCacheHitHookEventPayload {
277
+ value: any;
278
+ }
279
+ type OnCacheMissHook = () => void;
280
+ type OnCacheSetHook = (payload: OnCacheSetHookEventPayload) => MaybePromise$1<OnCacheSetHookResult | void>;
281
+ interface OnCacheSetHookResult {
282
+ onCacheSetDone?: () => void;
283
+ onCacheSetError?: OnCacheErrorHook;
284
+ }
285
+ interface OnCacheSetHookEventPayload {
286
+ cache: KeyValueCache;
287
+ key: string;
288
+ value: any;
289
+ ttl?: number;
290
+ }
291
+ type OnCacheDeleteHook = (payload: OnCacheDeleteHookEventPayload) => MaybePromise$1<OnCacheDeleteHookResult | void>;
292
+ interface OnCacheDeleteHookResult {
293
+ onCacheDeleteDone?: () => void;
294
+ onCacheDeleteError?: OnCacheErrorHook;
295
+ }
296
+ interface OnCacheDeleteHookEventPayload {
297
+ cache: KeyValueCache;
298
+ key: string;
299
+ }
300
+ type Instrumentation<TContext extends Record<string, any>> = Instrumentation$2<TContext> & Instrumentation$1 & FetchInstrumentation;
301
+
302
+ declare global {
303
+ var DEBUG: string;
304
+ }
305
+
306
+ declare function useDeduplicateRequest(): GatewayPlugin;
307
+
308
+ export { useDeduplicateRequest };
package/dist/index.js ADDED
@@ -0,0 +1,76 @@
1
+ import { getHeadersObj } from '@graphql-mesh/utils';
2
+ import { handleMaybePromise } from '@whatwg-node/promise-helpers';
3
+
4
+ function useDeduplicateRequest() {
5
+ const reqResMapByContext = /* @__PURE__ */ new WeakMap();
6
+ function getReqResMapByContext(context) {
7
+ let reqResMap = reqResMapByContext.get(context);
8
+ if (!reqResMap) {
9
+ reqResMap = /* @__PURE__ */ new Map();
10
+ reqResMapByContext.set(context, reqResMap);
11
+ }
12
+ return reqResMap;
13
+ }
14
+ const resPropMap = /* @__PURE__ */ new WeakMap();
15
+ return {
16
+ onFetch({ url, options, context, info, fetchFn, setFetchFn, endResponse }) {
17
+ if (context != null) {
18
+ let method = "GET";
19
+ if (options.method) {
20
+ method = options.method;
21
+ }
22
+ if (method === "GET") {
23
+ const reqResMap = getReqResMapByContext(context);
24
+ let dedupCacheKey = url;
25
+ if (options.headers) {
26
+ const headersObj = getHeadersObj(options.headers);
27
+ dedupCacheKey += JSON.stringify(headersObj);
28
+ }
29
+ const dedupRes$ = reqResMap.get(dedupCacheKey);
30
+ if (dedupRes$) {
31
+ endResponse(dedupRes$);
32
+ return;
33
+ }
34
+ setFetchFn(() => {
35
+ let dedupRes$2 = reqResMap.get(dedupCacheKey);
36
+ if (dedupRes$2 == null) {
37
+ dedupRes$2 = handleMaybePromise(
38
+ () => fetchFn(url, options, context, info),
39
+ (res) => {
40
+ let resPropMapByRes = resPropMap.get(res);
41
+ if (resPropMapByRes == null) {
42
+ resPropMapByRes = /* @__PURE__ */ new Map();
43
+ resPropMap.set(res, resPropMapByRes);
44
+ }
45
+ return new Proxy(res, {
46
+ get(target, prop) {
47
+ if (typeof target[prop] === "function") {
48
+ return (...args) => {
49
+ let resPropResult$ = resPropMapByRes.get(prop);
50
+ if (resPropResult$ == null) {
51
+ resPropResult$ = target[prop](...args);
52
+ resPropMapByRes.set(
53
+ prop,
54
+ // @ts-expect-error
55
+ resPropResult$
56
+ );
57
+ }
58
+ return resPropResult$;
59
+ };
60
+ }
61
+ return target[prop];
62
+ }
63
+ });
64
+ }
65
+ );
66
+ reqResMap.set(dedupCacheKey, dedupRes$2);
67
+ }
68
+ return dedupRes$2;
69
+ });
70
+ }
71
+ }
72
+ }
73
+ };
74
+ }
75
+
76
+ export { useDeduplicateRequest };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@graphql-hive/plugin-deduplicate-request",
3
+ "version": "1.0.0-alpha-74133153a0ea2263e454190ec9e3c2326e553396",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/graphql-hive/gateway.git",
8
+ "directory": "packages/plugins/deduplicate-request"
9
+ },
10
+ "author": {
11
+ "email": "contact@the-guild.dev",
12
+ "name": "The Guild",
13
+ "url": "https://the-guild.dev"
14
+ },
15
+ "license": "MIT",
16
+ "engines": {
17
+ "node": ">=18.0.0"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "require": {
24
+ "types": "./dist/index.d.cts",
25
+ "default": "./dist/index.cjs"
26
+ },
27
+ "import": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "scripts": {
38
+ "build": "pkgroll --clean-dist",
39
+ "prepack": "yarn build"
40
+ },
41
+ "peerDependencies": {
42
+ "graphql": "^16.9.0"
43
+ },
44
+ "dependencies": {
45
+ "@graphql-mesh/utils": "^0.104.3",
46
+ "@graphql-tools/utils": "^10.8.6",
47
+ "@whatwg-node/promise-helpers": "^1.3.1"
48
+ },
49
+ "devDependencies": {
50
+ "@graphql-hive/gateway-runtime": "1.8.2-alpha-74133153a0ea2263e454190ec9e3c2326e553396",
51
+ "@graphql-mesh/types": "^0.104.3",
52
+ "@whatwg-node/fetch": "^0.10.6",
53
+ "graphql": "^16.9.0",
54
+ "pkgroll": "2.12.2"
55
+ },
56
+ "sideEffects": false
57
+ }