@webiny/app 6.6.0-alpha.1 → 6.6.0-alpha.10
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/App.js +6 -1
- package/App.js.map +1 -1
- package/components/Image.d.ts +1 -1
- package/errors/GraphQLOperationError.d.ts +10 -0
- package/errors/GraphQLOperationError.js +11 -0
- package/errors/GraphQLOperationError.js.map +1 -0
- package/errors/__tests__/GraphQLOperationError.test.d.ts +1 -0
- package/errors/__tests__/GraphQLOperationError.test.js +97 -0
- package/errors/__tests__/GraphQLOperationError.test.js.map +1 -0
- package/errors/index.d.ts +2 -0
- package/errors/index.js +1 -0
- package/exports/admin.d.ts +2 -0
- package/exports/admin.js +2 -0
- package/features/apiRequestHeaders/ApiRequestHeadersResolver.d.ts +13 -0
- package/features/apiRequestHeaders/ApiRequestHeadersResolver.js +15 -0
- package/features/apiRequestHeaders/ApiRequestHeadersResolver.js.map +1 -0
- package/features/apiRequestHeaders/ApiStreamClientDecorator.d.ts +12 -0
- package/features/apiRequestHeaders/ApiStreamClientDecorator.js +25 -0
- package/features/apiRequestHeaders/ApiStreamClientDecorator.js.map +1 -0
- package/features/apiRequestHeaders/GraphQLClientDecorator.d.ts +12 -0
- package/features/apiRequestHeaders/GraphQLClientDecorator.js +25 -0
- package/features/apiRequestHeaders/GraphQLClientDecorator.js.map +1 -0
- package/features/apiRequestHeaders/__tests__/ApiRequestHeaders.test.d.ts +1 -0
- package/features/apiRequestHeaders/__tests__/ApiRequestHeaders.test.js +199 -0
- package/features/apiRequestHeaders/__tests__/ApiRequestHeaders.test.js.map +1 -0
- package/features/apiRequestHeaders/abstractions.d.ts +26 -0
- package/features/apiRequestHeaders/abstractions.js +6 -0
- package/features/apiRequestHeaders/abstractions.js.map +1 -0
- package/features/apiRequestHeaders/feature.d.ts +6 -0
- package/features/apiRequestHeaders/feature.js +16 -0
- package/features/apiRequestHeaders/feature.js.map +1 -0
- package/features/apiRequestHeaders/index.d.ts +2 -0
- package/features/apiRequestHeaders/index.js +2 -0
- package/features/apiRequestHeaders/mergeHeaders.d.ts +13 -0
- package/features/apiRequestHeaders/mergeHeaders.js +20 -0
- package/features/apiRequestHeaders/mergeHeaders.js.map +1 -0
- package/features/graphqlClient/BatchingGraphQLClient.d.ts +3 -1
- package/features/graphqlClient/BatchingGraphQLClient.js +13 -3
- package/features/graphqlClient/BatchingGraphQLClient.js.map +1 -1
- package/features/graphqlClient/FetchGraphQLClient.d.ts +3 -0
- package/features/graphqlClient/FetchGraphQLClient.js +18 -4
- package/features/graphqlClient/FetchGraphQLClient.js.map +1 -1
- package/features/graphqlClient/GraphQLExtensionsEvent.d.ts +18 -0
- package/features/graphqlClient/GraphQLExtensionsEvent.js +13 -0
- package/features/graphqlClient/GraphQLExtensionsEvent.js.map +1 -0
- package/features/graphqlClient/__tests__/GraphQLClient.test.js +202 -0
- package/features/graphqlClient/__tests__/GraphQLClient.test.js.map +1 -1
- package/features/graphqlClient/abstractions.d.ts +7 -0
- package/features/graphqlClient/abstractions.js +2 -1
- package/features/graphqlClient/abstractions.js.map +1 -1
- package/features/graphqlClient/index.d.ts +3 -0
- package/features/graphqlClient/index.js +2 -1
- package/features/graphqlClient/publishExtensions.d.ts +13 -0
- package/features/graphqlClient/publishExtensions.js +16 -0
- package/features/graphqlClient/publishExtensions.js.map +1 -0
- package/features/router/HistoryRouterGateway.test.js +68 -0
- package/features/router/HistoryRouterGateway.test.js.map +1 -1
- package/features/router/Router.d.ts +9 -2
- package/features/router/Router.js +4 -5
- package/features/router/Router.js.map +1 -1
- package/package.json +17 -17
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createAbstraction } from "@webiny/feature/admin";
|
|
2
|
+
const ApiRequestHeaders = createAbstraction("ApiRequestHeaders");
|
|
3
|
+
const ApiRequestHeadersResolver = createAbstraction("ApiRequestHeadersResolver");
|
|
4
|
+
export { ApiRequestHeaders, ApiRequestHeadersResolver };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=abstractions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiRequestHeaders/abstractions.js","sources":["../../../src/features/apiRequestHeaders/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/admin\";\n\ntype IHeaders = Record<string, string | number | undefined>;\n\n/**\n * Extra headers for every request to Webiny's API (`GraphQLClient` and `ApiStreamClient`), read when\n * a request is sent. An extension registers one for a header the API needs on each request, e.g. a\n * scope its own decorators read. Headers the request sets itself (tenant, auth, …) win.\n *\n * Register it in the root container (as `RegisterFeature` does): the clients look providers up there.\n * Only for Webiny's API: requests to other hosts (storage uploads, identity providers) don't get them.\n */\nexport interface IApiRequestHeaders {\n getHeaders(): IHeaders | Promise<IHeaders>;\n}\n\nexport const ApiRequestHeaders = createAbstraction<IApiRequestHeaders>(\"ApiRequestHeaders\");\n\nexport namespace ApiRequestHeaders {\n export type Interface = IApiRequestHeaders;\n export type Headers = IHeaders;\n}\n\n/** The headers of every registered `ApiRequestHeaders`, collected for one request. */\nexport interface IApiRequestHeadersResolver {\n resolve(): Promise<IHeaders>;\n}\n\nexport const ApiRequestHeadersResolver = createAbstraction<IApiRequestHeadersResolver>(\n \"ApiRequestHeadersResolver\"\n);\n\nexport namespace ApiRequestHeadersResolver {\n export type Interface = IApiRequestHeadersResolver;\n}\n"],"names":["ApiRequestHeaders","createAbstraction","ApiRequestHeadersResolver"],"mappings":";AAgBO,MAAMA,oBAAoBC,kBAAsC;AAYhE,MAAMC,4BAA4BD,kBACrC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adds every `ApiRequestHeaders` provider's headers to requests to Webiny's API. Register it after
|
|
3
|
+
* the clients and before the decorators that add the tenant and auth headers, so those wrap it and
|
|
4
|
+
* win over a provider's header of the same name.
|
|
5
|
+
*/
|
|
6
|
+
export declare const ApiRequestHeadersFeature: import("@webiny/feature/admin").FeatureDefinition<any, []>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createFeature } from "@webiny/feature/admin";
|
|
2
|
+
import { ApiRequestHeadersResolver } from "./abstractions.js";
|
|
3
|
+
import { ApiRequestHeadersResolver as external_ApiRequestHeadersResolver_js_ApiRequestHeadersResolver } from "./ApiRequestHeadersResolver.js";
|
|
4
|
+
import { ApiStreamClientDecorator } from "./ApiStreamClientDecorator.js";
|
|
5
|
+
import { GraphQLClientDecorator } from "./GraphQLClientDecorator.js";
|
|
6
|
+
const ApiRequestHeadersFeature = createFeature({
|
|
7
|
+
name: "ApiRequestHeaders",
|
|
8
|
+
register (container) {
|
|
9
|
+
container.registerInstance(ApiRequestHeadersResolver, new external_ApiRequestHeadersResolver_js_ApiRequestHeadersResolver(container));
|
|
10
|
+
container.registerDecorator(GraphQLClientDecorator);
|
|
11
|
+
container.registerDecorator(ApiStreamClientDecorator);
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
export { ApiRequestHeadersFeature };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=feature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiRequestHeaders/feature.js","sources":["../../../src/features/apiRequestHeaders/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/admin\";\nimport type { Container } from \"@webiny/di\";\nimport { ApiRequestHeadersResolver as ResolverAbstraction } from \"./abstractions.js\";\nimport { ApiRequestHeadersResolver } from \"./ApiRequestHeadersResolver.js\";\nimport { ApiStreamClientDecorator } from \"./ApiStreamClientDecorator.js\";\nimport { GraphQLClientDecorator } from \"./GraphQLClientDecorator.js\";\n\n/**\n * Adds every `ApiRequestHeaders` provider's headers to requests to Webiny's API. Register it after\n * the clients and before the decorators that add the tenant and auth headers, so those wrap it and\n * win over a provider's header of the same name.\n */\nexport const ApiRequestHeadersFeature = createFeature({\n name: \"ApiRequestHeaders\",\n register(container: Container) {\n container.registerInstance(ResolverAbstraction, new ApiRequestHeadersResolver(container));\n container.registerDecorator(GraphQLClientDecorator);\n container.registerDecorator(ApiStreamClientDecorator);\n }\n});\n"],"names":["ApiRequestHeadersFeature","createFeature","container","ResolverAbstraction","ApiRequestHeadersResolver","GraphQLClientDecorator","ApiStreamClientDecorator"],"mappings":";;;;;AAYO,MAAMA,2BAA2BC,cAAc;IAClD,MAAM;IACN,UAASC,SAAoB;QACzBA,UAAU,gBAAgB,CAACC,2BAAqB,IAAIC,gEAA0BF;QAC9EA,UAAU,iBAAiB,CAACG;QAC5BH,UAAU,iBAAiB,CAACI;IAChC;AACJ"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ApiRequestHeaders } from "./abstractions.js";
|
|
2
|
+
type Headers = ApiRequestHeaders.Headers;
|
|
3
|
+
/**
|
|
4
|
+
* The providers' headers merged in order: a later provider's value replaces an earlier one's, whatever
|
|
5
|
+
* the case of the name (header names are case-insensitive). An undefined value means "no header".
|
|
6
|
+
*/
|
|
7
|
+
export declare function mergeProviderHeaders(results: Array<Headers | undefined>): Headers;
|
|
8
|
+
/**
|
|
9
|
+
* The request's own headers (and those of the decorators around this one) win over the providers', whatever
|
|
10
|
+
* the case of the name.
|
|
11
|
+
*/
|
|
12
|
+
export declare function withProviderHeaders(provided: Headers, own: Headers | undefined): Headers;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
function mergeProviderHeaders(results) {
|
|
2
|
+
const merged = new Map();
|
|
3
|
+
for (const result of results)for (const [name, value] of Object.entries(result ?? {}))if (void 0 !== value) merged.set(name.toLowerCase(), [
|
|
4
|
+
name,
|
|
5
|
+
value
|
|
6
|
+
]);
|
|
7
|
+
return Object.fromEntries(merged.values());
|
|
8
|
+
}
|
|
9
|
+
function withProviderHeaders(provided, own) {
|
|
10
|
+
const ownNames = new Set(Object.keys(own ?? {}).map((name)=>name.toLowerCase()));
|
|
11
|
+
const headers = {};
|
|
12
|
+
for (const [name, value] of Object.entries(provided))if (!ownNames.has(name.toLowerCase())) headers[name] = value;
|
|
13
|
+
return {
|
|
14
|
+
...headers,
|
|
15
|
+
...own
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export { mergeProviderHeaders, withProviderHeaders };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=mergeHeaders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiRequestHeaders/mergeHeaders.js","sources":["../../../src/features/apiRequestHeaders/mergeHeaders.ts"],"sourcesContent":["import type { ApiRequestHeaders } from \"./abstractions.js\";\n\ntype Headers = ApiRequestHeaders.Headers;\n\n/**\n * The providers' headers merged in order: a later provider's value replaces an earlier one's, whatever\n * the case of the name (header names are case-insensitive). An undefined value means \"no header\".\n */\nexport function mergeProviderHeaders(results: Array<Headers | undefined>): Headers {\n const merged = new Map<string, [string, string | number]>();\n for (const result of results) {\n for (const [name, value] of Object.entries(result ?? {})) {\n if (value !== undefined) {\n merged.set(name.toLowerCase(), [name, value]);\n }\n }\n }\n return Object.fromEntries(merged.values());\n}\n\n/**\n * The request's own headers (and those of the decorators around this one) win over the providers', whatever\n * the case of the name.\n */\nexport function withProviderHeaders(provided: Headers, own: Headers | undefined): Headers {\n const ownNames = new Set(Object.keys(own ?? {}).map(name => name.toLowerCase()));\n const headers: Headers = {};\n for (const [name, value] of Object.entries(provided)) {\n if (!ownNames.has(name.toLowerCase())) {\n headers[name] = value;\n }\n }\n return { ...headers, ...own };\n}\n"],"names":["mergeProviderHeaders","results","merged","Map","result","name","value","Object","undefined","withProviderHeaders","provided","own","ownNames","Set","headers"],"mappings":"AAQO,SAASA,qBAAqBC,OAAmC;IACpE,MAAMC,SAAS,IAAIC;IACnB,KAAK,MAAMC,UAAUH,QACjB,KAAK,MAAM,CAACI,MAAMC,MAAM,IAAIC,OAAO,OAAO,CAACH,UAAU,CAAC,GAClD,IAAIE,AAAUE,WAAVF,OACAJ,OAAO,GAAG,CAACG,KAAK,WAAW,IAAI;QAACA;QAAMC;KAAM;IAIxD,OAAOC,OAAO,WAAW,CAACL,OAAO,MAAM;AAC3C;AAMO,SAASO,oBAAoBC,QAAiB,EAAEC,GAAwB;IAC3E,MAAMC,WAAW,IAAIC,IAAIN,OAAO,IAAI,CAACI,OAAO,CAAC,GAAG,GAAG,CAACN,CAAAA,OAAQA,KAAK,WAAW;IAC5E,MAAMS,UAAmB,CAAC;IAC1B,KAAK,MAAM,CAACT,MAAMC,MAAM,IAAIC,OAAO,OAAO,CAACG,UACvC,IAAI,CAACE,SAAS,GAAG,CAACP,KAAK,WAAW,KAC9BS,OAAO,CAACT,KAAK,GAAGC;IAGxB,OAAO;QAAE,GAAGQ,OAAO;QAAE,GAAGH,GAAG;IAAC;AAChC"}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { GraphQLClient } from "./abstractions.js";
|
|
2
|
+
import { EventPublisher } from "../../features/eventPublisher/index.js";
|
|
2
3
|
declare class BatchingGraphQLClientImpl implements GraphQLClient.Interface {
|
|
4
|
+
private eventPublisher;
|
|
3
5
|
private decoratee;
|
|
4
6
|
private queue;
|
|
5
7
|
private batchTimeout;
|
|
6
8
|
private readonly batchWindowMs;
|
|
7
9
|
private readonly maxBatchSize;
|
|
8
|
-
constructor(decoratee: GraphQLClient.Interface);
|
|
10
|
+
constructor(eventPublisher: EventPublisher.Interface, decoratee: GraphQLClient.Interface);
|
|
9
11
|
execute<TVariables = any, TResult = any>(params: GraphQLClient.Request<TVariables>): Promise<TResult>;
|
|
10
12
|
private flush;
|
|
11
13
|
private executeBatchGroup;
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { createDecorator } from "@webiny/di";
|
|
2
2
|
import { GraphQLClient } from "./abstractions.js";
|
|
3
3
|
import { RequestValue } from "./RequestValue.js";
|
|
4
|
+
import { EventPublisher } from "../eventPublisher/index.js";
|
|
5
|
+
import { publishExtensions } from "./publishExtensions.js";
|
|
4
6
|
class BatchingGraphQLClientImpl {
|
|
5
|
-
constructor(decoratee){
|
|
7
|
+
constructor(eventPublisher, decoratee){
|
|
8
|
+
this.eventPublisher = eventPublisher;
|
|
6
9
|
this.decoratee = decoratee;
|
|
7
10
|
this.queue = [];
|
|
8
11
|
this.batchTimeout = null;
|
|
@@ -102,8 +105,13 @@ class BatchingGraphQLClientImpl {
|
|
|
102
105
|
throw new Error("Failed to parse GraphQL batch response as JSON.");
|
|
103
106
|
}
|
|
104
107
|
if (!Array.isArray(json)) throw new Error("Expected batch response to be an array");
|
|
108
|
+
for (const [index, result] of json.entries())await publishExtensions(this.eventPublisher, {
|
|
109
|
+
endpoint,
|
|
110
|
+
operationName: operations[index]?.operationName,
|
|
111
|
+
extensions: result?.extensions
|
|
112
|
+
});
|
|
105
113
|
return json.map((result, index)=>{
|
|
106
|
-
if (result.errors && result.errors.length > 0) throw new Error(`GraphQL errors in operation ${index}: ${JSON.stringify(result.errors)}`);
|
|
114
|
+
if (result.errors && result.errors.length > 0 && !result.data) throw new Error(`GraphQL errors in operation ${index}: ${JSON.stringify(result.errors)}`);
|
|
107
115
|
return result.data;
|
|
108
116
|
});
|
|
109
117
|
}
|
|
@@ -111,7 +119,9 @@ class BatchingGraphQLClientImpl {
|
|
|
111
119
|
const BatchingGraphQLClient = createDecorator({
|
|
112
120
|
abstraction: GraphQLClient,
|
|
113
121
|
decorator: BatchingGraphQLClientImpl,
|
|
114
|
-
dependencies: [
|
|
122
|
+
dependencies: [
|
|
123
|
+
EventPublisher
|
|
124
|
+
]
|
|
115
125
|
});
|
|
116
126
|
export { BatchingGraphQLClient };
|
|
117
127
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/graphqlClient/BatchingGraphQLClient.js","sources":["../../../src/features/graphqlClient/BatchingGraphQLClient.ts"],"sourcesContent":["import { createDecorator } from \"@webiny/di\";\nimport { GraphQLClient } from \"./abstractions.js\";\nimport { RequestValue } from \"~/features/graphqlClient/RequestValue.js\";\n\ninterface BatchedRequest {\n request: RequestValue;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n}\n\ninterface BatchOperation {\n operationName: string | undefined;\n query: string;\n variables?: any;\n}\n\nclass BatchingGraphQLClientImpl implements GraphQLClient.Interface {\n private queue: BatchedRequest[] = [];\n private batchTimeout: NodeJS.Timeout | null = null;\n private readonly batchWindowMs: number;\n private readonly maxBatchSize: number;\n\n constructor(private decoratee: GraphQLClient.Interface) {\n // Default: 10ms window, max 10 operations per batch\n this.batchWindowMs = 10;\n this.maxBatchSize = 10;\n }\n\n async execute<TVariables = any, TResult = any>(\n params: GraphQLClient.Request<TVariables>\n ): Promise<TResult> {\n return new Promise((resolve, reject) => {\n this.queue.push({ request: RequestValue.from(params), resolve, reject });\n\n if (this.queue.length >= this.maxBatchSize) {\n this.flush();\n return;\n }\n\n if (!this.batchTimeout) {\n this.batchTimeout = setTimeout(() => {\n this.flush();\n }, this.batchWindowMs);\n }\n });\n }\n\n private async flush(): Promise<void> {\n if (this.batchTimeout) {\n clearTimeout(this.batchTimeout);\n this.batchTimeout = null;\n }\n\n if (this.queue.length === 0) {\n return;\n }\n\n const batch = this.queue.splice(0, this.queue.length);\n\n // Single request - use decoratee directly (no batching needed)\n if (batch.length === 1) {\n const { request, resolve, reject } = batch[0];\n try {\n const result = await this.decoratee.execute(request.request);\n resolve(result);\n } catch (error) {\n reject(error);\n }\n return;\n }\n\n // Group requests by endpoint + headers (only batch requests with identical target)\n const grouped = new Map<string, BatchedRequest[]>();\n for (const item of batch) {\n const groupKey =\n item.request.endpoint + \"|\" + this.serializeHeaders(item.request.headers);\n if (!grouped.has(groupKey)) {\n grouped.set(groupKey, []);\n }\n grouped.get(groupKey)!.push(item);\n }\n\n // Process each group separately\n const batchPromises = Array.from(grouped.entries()).map(requests => {\n const group = requests[1];\n\n if (group.length === 1) {\n // Single request in this group - use decoratee directly\n const { request, resolve, reject } = group[0];\n return this.decoratee.execute(request.request).then(resolve).catch(reject);\n }\n\n // Multiple requests with same headers - batch them\n return this.executeBatchGroup(group);\n });\n\n await Promise.all(batchPromises);\n }\n\n private async executeBatchGroup(group: BatchedRequest[]): Promise<void> {\n const batchedOperations = group.map(({ request }): BatchOperation => {\n return {\n query: request.queryAsString,\n operationName: request.operationName,\n variables: request.variables\n };\n });\n\n const endpoint = group[0].request.endpoint;\n const headers = group[0].request.headers;\n\n try {\n const results = await this.executeBatch(endpoint, batchedOperations, headers);\n group.forEach(({ resolve }, index) => {\n resolve(results[index]);\n });\n } catch (error) {\n group.forEach(({ reject }) => {\n reject(error);\n });\n }\n }\n\n private serializeHeaders(headers?: GraphQLClient.Headers): string {\n if (!headers) {\n return \"{}\";\n }\n // Sort keys for consistent serialization\n const sortedKeys = Object.keys(headers).sort();\n const sortedHeaders: Record<string, string> = {};\n for (const key of sortedKeys) {\n sortedHeaders[key] = String(headers[key]);\n }\n return JSON.stringify(sortedHeaders);\n }\n\n private async executeBatch(\n endpoint: string,\n operations: BatchOperation[],\n headers?: GraphQLClient.Headers\n ): Promise<any[]> {\n let response: Response;\n\n try {\n response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(headers || {})\n },\n body: JSON.stringify(operations)\n });\n } catch (err) {\n throw new Error(`Network error: ${(err as Error).message}`);\n }\n\n let json: any;\n try {\n json = await response.json();\n } catch {\n throw new Error(\"Failed to parse GraphQL batch response as JSON.\");\n }\n\n if (!Array.isArray(json)) {\n throw new Error(\"Expected batch response to be an array\");\n }\n\n // Map each result, handling individual errors\n return json.map((result: any, index: number) => {\n if (result.errors && result.errors.length > 0) {\n throw new Error(\n `GraphQL errors in operation ${index}: ${JSON.stringify(result.errors)}`\n );\n }\n return result.data;\n });\n }\n}\n\nexport const BatchingGraphQLClient = createDecorator({\n abstraction: GraphQLClient,\n decorator: BatchingGraphQLClientImpl,\n dependencies: []\n});\n"],"names":["BatchingGraphQLClientImpl","decoratee","params","Promise","resolve","reject","RequestValue","setTimeout","clearTimeout","batch","request","result","error","grouped","Map","item","groupKey","batchPromises","Array","requests","group","batchedOperations","endpoint","headers","results","index","sortedKeys","Object","sortedHeaders","key","String","JSON","operations","response","fetch","err","Error","json","BatchingGraphQLClient","createDecorator","GraphQLClient"],"mappings":";;;AAgBA,MAAMA;IAMF,YAAoBC,SAAkC,CAAE;aAApCA,SAAS,GAATA;aALZ,KAAK,GAAqB,EAAE;aAC5B,YAAY,GAA0B;QAM1C,IAAI,CAAC,aAAa,GAAG;QACrB,IAAI,CAAC,YAAY,GAAG;IACxB;IAEA,MAAM,QACFC,MAAyC,EACzB;QAChB,OAAO,IAAIC,QAAQ,CAACC,SAASC;YACzB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;gBAAE,SAASC,aAAa,IAAI,CAACJ;gBAASE;gBAASC;YAAO;YAEtE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,EAAE,YACxC,IAAI,CAAC,KAAK;YAId,IAAI,CAAC,IAAI,CAAC,YAAY,EAClB,IAAI,CAAC,YAAY,GAAGE,WAAW;gBAC3B,IAAI,CAAC,KAAK;YACd,GAAG,IAAI,CAAC,aAAa;QAE7B;IACJ;IAEA,MAAc,QAAuB;QACjC,IAAI,IAAI,CAAC,YAAY,EAAE;YACnBC,aAAa,IAAI,CAAC,YAAY;YAC9B,IAAI,CAAC,YAAY,GAAG;QACxB;QAEA,IAAI,AAAsB,MAAtB,IAAI,CAAC,KAAK,CAAC,MAAM,EACjB;QAGJ,MAAMC,QAAQ,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM;QAGpD,IAAIA,AAAiB,MAAjBA,MAAM,MAAM,EAAQ;YACpB,MAAM,EAAEC,OAAO,EAAEN,OAAO,EAAEC,MAAM,EAAE,GAAGI,KAAK,CAAC,EAAE;YAC7C,IAAI;gBACA,MAAME,SAAS,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAACD,QAAQ,OAAO;gBAC3DN,QAAQO;YACZ,EAAE,OAAOC,OAAO;gBACZP,OAAOO;YACX;YACA;QACJ;QAGA,MA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
{"version":3,"file":"features/graphqlClient/BatchingGraphQLClient.js","sources":["../../../src/features/graphqlClient/BatchingGraphQLClient.ts"],"sourcesContent":["import { createDecorator } from \"@webiny/di\";\nimport { GraphQLClient } from \"./abstractions.js\";\nimport { RequestValue } from \"~/features/graphqlClient/RequestValue.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { publishExtensions } from \"./publishExtensions.js\";\n\ninterface BatchedRequest {\n request: RequestValue;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n}\n\ninterface BatchOperation {\n operationName: string | undefined;\n query: string;\n variables?: any;\n}\n\nclass BatchingGraphQLClientImpl implements GraphQLClient.Interface {\n private queue: BatchedRequest[] = [];\n private batchTimeout: NodeJS.Timeout | null = null;\n private readonly batchWindowMs: number;\n private readonly maxBatchSize: number;\n\n constructor(\n private eventPublisher: EventPublisher.Interface,\n private decoratee: GraphQLClient.Interface\n ) {\n // Default: 10ms window, max 10 operations per batch\n this.batchWindowMs = 10;\n this.maxBatchSize = 10;\n }\n\n async execute<TVariables = any, TResult = any>(\n params: GraphQLClient.Request<TVariables>\n ): Promise<TResult> {\n return new Promise((resolve, reject) => {\n this.queue.push({ request: RequestValue.from(params), resolve, reject });\n\n if (this.queue.length >= this.maxBatchSize) {\n this.flush();\n return;\n }\n\n if (!this.batchTimeout) {\n this.batchTimeout = setTimeout(() => {\n this.flush();\n }, this.batchWindowMs);\n }\n });\n }\n\n private async flush(): Promise<void> {\n if (this.batchTimeout) {\n clearTimeout(this.batchTimeout);\n this.batchTimeout = null;\n }\n\n if (this.queue.length === 0) {\n return;\n }\n\n const batch = this.queue.splice(0, this.queue.length);\n\n // Single request - use decoratee directly (no batching needed)\n if (batch.length === 1) {\n const { request, resolve, reject } = batch[0];\n try {\n const result = await this.decoratee.execute(request.request);\n resolve(result);\n } catch (error) {\n reject(error);\n }\n return;\n }\n\n // Group requests by endpoint + headers (only batch requests with identical target)\n const grouped = new Map<string, BatchedRequest[]>();\n for (const item of batch) {\n const groupKey =\n item.request.endpoint + \"|\" + this.serializeHeaders(item.request.headers);\n if (!grouped.has(groupKey)) {\n grouped.set(groupKey, []);\n }\n grouped.get(groupKey)!.push(item);\n }\n\n // Process each group separately\n const batchPromises = Array.from(grouped.entries()).map(requests => {\n const group = requests[1];\n\n if (group.length === 1) {\n // Single request in this group - use decoratee directly\n const { request, resolve, reject } = group[0];\n return this.decoratee.execute(request.request).then(resolve).catch(reject);\n }\n\n // Multiple requests with same headers - batch them\n return this.executeBatchGroup(group);\n });\n\n await Promise.all(batchPromises);\n }\n\n private async executeBatchGroup(group: BatchedRequest[]): Promise<void> {\n const batchedOperations = group.map(({ request }): BatchOperation => {\n return {\n query: request.queryAsString,\n operationName: request.operationName,\n variables: request.variables\n };\n });\n\n const endpoint = group[0].request.endpoint;\n const headers = group[0].request.headers;\n\n try {\n const results = await this.executeBatch(endpoint, batchedOperations, headers);\n group.forEach(({ resolve }, index) => {\n resolve(results[index]);\n });\n } catch (error) {\n group.forEach(({ reject }) => {\n reject(error);\n });\n }\n }\n\n private serializeHeaders(headers?: GraphQLClient.Headers): string {\n if (!headers) {\n return \"{}\";\n }\n // Sort keys for consistent serialization\n const sortedKeys = Object.keys(headers).sort();\n const sortedHeaders: Record<string, string> = {};\n for (const key of sortedKeys) {\n sortedHeaders[key] = String(headers[key]);\n }\n return JSON.stringify(sortedHeaders);\n }\n\n private async executeBatch(\n endpoint: string,\n operations: BatchOperation[],\n headers?: GraphQLClient.Headers\n ): Promise<any[]> {\n let response: Response;\n\n try {\n response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(headers || {})\n },\n body: JSON.stringify(operations)\n });\n } catch (err) {\n throw new Error(`Network error: ${(err as Error).message}`);\n }\n\n let json: any;\n try {\n json = await response.json();\n } catch {\n throw new Error(\"Failed to parse GraphQL batch response as JSON.\");\n }\n\n if (!Array.isArray(json)) {\n throw new Error(\"Expected batch response to be an array\");\n }\n\n /*\n * The batch went out in one request, so it bypassed the decoratee that would otherwise have\n * announced each response's extensions. Announced before the error handling below, which\n * can fail the whole batch: a failed operation is exactly the one whose debug data is wanted.\n */\n for (const [index, result] of json.entries()) {\n await publishExtensions(this.eventPublisher, {\n endpoint,\n operationName: operations[index]?.operationName,\n extensions: result?.extensions\n });\n }\n\n // Map each result, handling individual errors. As with the non-batched client, a result\n // may carry both `data` and `errors` (partial success); we only fail an operation when it\n // produced no data at all, otherwise the partial payload is handed back to its caller.\n return json.map((result: any, index: number) => {\n if (result.errors && result.errors.length > 0 && !result.data) {\n throw new Error(\n `GraphQL errors in operation ${index}: ${JSON.stringify(result.errors)}`\n );\n }\n return result.data;\n });\n }\n}\n\nexport const BatchingGraphQLClient = createDecorator({\n abstraction: GraphQLClient,\n decorator: BatchingGraphQLClientImpl,\n dependencies: [EventPublisher]\n});\n"],"names":["BatchingGraphQLClientImpl","eventPublisher","decoratee","params","Promise","resolve","reject","RequestValue","setTimeout","clearTimeout","batch","request","result","error","grouped","Map","item","groupKey","batchPromises","Array","requests","group","batchedOperations","endpoint","headers","results","index","sortedKeys","Object","sortedHeaders","key","String","JSON","operations","response","fetch","err","Error","json","publishExtensions","BatchingGraphQLClient","createDecorator","GraphQLClient","EventPublisher"],"mappings":";;;;;AAkBA,MAAMA;IAMF,YACYC,cAAwC,EACxCC,SAAkC,CAC5C;aAFUD,cAAc,GAAdA;aACAC,SAAS,GAATA;aAPJ,KAAK,GAAqB,EAAE;aAC5B,YAAY,GAA0B;QAS1C,IAAI,CAAC,aAAa,GAAG;QACrB,IAAI,CAAC,YAAY,GAAG;IACxB;IAEA,MAAM,QACFC,MAAyC,EACzB;QAChB,OAAO,IAAIC,QAAQ,CAACC,SAASC;YACzB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;gBAAE,SAASC,aAAa,IAAI,CAACJ;gBAASE;gBAASC;YAAO;YAEtE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,EAAE,YACxC,IA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gBAC7B,QAAQ;gBACR,SAAS;oBACL,gBAAgB;oBAChB,GAAIC,WAAW,CAAC,CAAC;gBACrB;gBACA,MAAMQ,KAAK,SAAS,CAACC;YACzB;QACJ,EAAE,OAAOG,KAAK;YACV,MAAM,IAAIC,MAAM,CAAC,eAAe,EAAGD,IAAc,OAAO,EAAE;QAC9D;QAEA,IAAIE;QACJ,IAAI;YACAA,OAAO,MAAMJ,SAAS,IAAI;QAC9B,EAAE,OAAM;YACJ,MAAM,IAAIG,MAAM;QACpB;QAEA,IAAI,CAAClB,MAAM,OAAO,CAACmB,OACf,MAAM,IAAID,MAAM;QAQpB,KAAK,MAAM,CAACX,OAAOd,OAAO,IAAI0B,KAAK,OAAO,GACtC,MAAMC,kBAAkB,IAAI,CAAC,cAAc,EAAE;YACzChB;YACA,eAAeU,UAAU,CAACP,MAAM,EAAE;YAClC,YAAYd,QAAQ;QACxB;QAMJ,OAAO0B,KAAK,GAAG,CAAC,CAAC1B,QAAac;YAC1B,IAAId,OAAO,MAAM,IAAIA,OAAO,MAAM,CAAC,MAAM,GAAG,KAAK,CAACA,OAAO,IAAI,EACzD,MAAM,IAAIyB,MACN,CAAC,4BAA4B,EAAEX,MAAM,EAAE,EAAEM,KAAK,SAAS,CAACpB,OAAO,MAAM,GAAG;YAGhF,OAAOA,OAAO,IAAI;QACtB;IACJ;AACJ;AAEO,MAAM4B,wBAAwBC,gBAAgB;IACjD,aAAaC;IACb,WAAW1C;IACX,cAAc;QAAC2C;KAAe;AAClC"}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { GraphQLClient } from "./abstractions.js";
|
|
2
|
+
import { EventPublisher } from "../../features/eventPublisher/index.js";
|
|
2
3
|
declare class GraphQLClientImpl implements GraphQLClient.Interface {
|
|
4
|
+
private eventPublisher;
|
|
5
|
+
constructor(eventPublisher: EventPublisher.Interface);
|
|
3
6
|
execute<TResult = any, TVariables = any>(params: GraphQLClient.Request<TVariables>): Promise<TResult>;
|
|
4
7
|
private fetch;
|
|
5
8
|
}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { createImplementation } from "@webiny/di";
|
|
2
2
|
import { GraphQLClient } from "./abstractions.js";
|
|
3
3
|
import { RequestValue } from "./RequestValue.js";
|
|
4
|
+
import { EventPublisher } from "../eventPublisher/index.js";
|
|
5
|
+
import { publishExtensions } from "./publishExtensions.js";
|
|
4
6
|
class GraphQLClientImpl {
|
|
7
|
+
constructor(eventPublisher){
|
|
8
|
+
this.eventPublisher = eventPublisher;
|
|
9
|
+
}
|
|
5
10
|
async execute(params) {
|
|
6
11
|
const request = RequestValue.from(params);
|
|
7
12
|
const body = JSON.stringify({
|
|
@@ -9,9 +14,11 @@ class GraphQLClientImpl {
|
|
|
9
14
|
variables: request.variables,
|
|
10
15
|
operationName: request.operationName
|
|
11
16
|
});
|
|
12
|
-
return this.fetch(request
|
|
17
|
+
return this.fetch(request, body);
|
|
13
18
|
}
|
|
14
|
-
async fetch(
|
|
19
|
+
async fetch(request, body) {
|
|
20
|
+
const endpoint = request.endpoint;
|
|
21
|
+
const headers = request.headers;
|
|
15
22
|
let response;
|
|
16
23
|
try {
|
|
17
24
|
response = await fetch(endpoint, {
|
|
@@ -35,7 +42,12 @@ class GraphQLClientImpl {
|
|
|
35
42
|
message: json.message,
|
|
36
43
|
code: json.code
|
|
37
44
|
};
|
|
38
|
-
|
|
45
|
+
await publishExtensions(this.eventPublisher, {
|
|
46
|
+
endpoint,
|
|
47
|
+
operationName: request.operationName,
|
|
48
|
+
extensions: json.extensions
|
|
49
|
+
});
|
|
50
|
+
if (json.errors && json.errors.length > 0 && !json.data) throw new Error("GraphQL errors", {
|
|
39
51
|
cause: json.errors
|
|
40
52
|
});
|
|
41
53
|
return json.data;
|
|
@@ -44,7 +56,9 @@ class GraphQLClientImpl {
|
|
|
44
56
|
const FetchGraphQLClient = createImplementation({
|
|
45
57
|
abstraction: GraphQLClient,
|
|
46
58
|
implementation: GraphQLClientImpl,
|
|
47
|
-
dependencies: [
|
|
59
|
+
dependencies: [
|
|
60
|
+
EventPublisher
|
|
61
|
+
]
|
|
48
62
|
});
|
|
49
63
|
export { FetchGraphQLClient };
|
|
50
64
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/graphqlClient/FetchGraphQLClient.js","sources":["../../../src/features/graphqlClient/FetchGraphQLClient.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { GraphQLClient } from \"./abstractions.js\";\nimport { RequestValue } from \"~/features/graphqlClient/RequestValue.js\";\n\nclass GraphQLClientImpl implements GraphQLClient.Interface {\n async execute<TResult = any, TVariables = any>(\n params: GraphQLClient.Request<TVariables>\n ): Promise<TResult> {\n const request = RequestValue.from(params);\n\n const body = JSON.stringify({\n query: request.queryAsString,\n variables: request.variables,\n operationName: request.operationName\n });\n\n return this.fetch<TResult>(request
|
|
1
|
+
{"version":3,"file":"features/graphqlClient/FetchGraphQLClient.js","sources":["../../../src/features/graphqlClient/FetchGraphQLClient.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { GraphQLClient } from \"./abstractions.js\";\nimport { RequestValue } from \"~/features/graphqlClient/RequestValue.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { publishExtensions } from \"./publishExtensions.js\";\n\nclass GraphQLClientImpl implements GraphQLClient.Interface {\n constructor(private eventPublisher: EventPublisher.Interface) {}\n\n async execute<TResult = any, TVariables = any>(\n params: GraphQLClient.Request<TVariables>\n ): Promise<TResult> {\n const request = RequestValue.from(params);\n\n const body = JSON.stringify({\n query: request.queryAsString,\n variables: request.variables,\n operationName: request.operationName\n });\n\n return this.fetch<TResult>(request, body);\n }\n\n private async fetch<TResult = any>(request: RequestValue, body: string): Promise<TResult> {\n const endpoint = request.endpoint;\n const headers = request.headers;\n let response: Response;\n try {\n response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(headers || {})\n },\n body\n });\n } catch (err) {\n throw new Error(`Network error: ${(err as Error).message}`);\n }\n let json: any;\n try {\n json = await response.json();\n } catch {\n throw new Error(\"Failed to parse GraphQL response as JSON.\");\n }\n\n // Check for generic API errors\n if (response.status !== 200) {\n throw { message: json.message, code: json.code };\n }\n\n /*\n * `execute` returns only `data`, so this is the one place the response's extensions are\n * still in reach. Announced before the error check below: a failed operation is exactly\n * the one whose debug data is wanted.\n */\n await publishExtensions(this.eventPublisher, {\n endpoint,\n operationName: request.operationName,\n extensions: json.extensions\n });\n\n /**\n * A GraphQL response can carry BOTH `data` and `errors` (partial success): a non-nullable\n * field error nulls that field and bubbles up to the nearest nullable ancestor, while the\n * rest of `data` stays valid and usable. We only treat errors as fatal when there is no\n * data to return — otherwise callers are free to consume the partial payload.\n */\n if (json.errors && json.errors.length > 0 && !json.data) {\n throw new Error(`GraphQL errors`, { cause: json.errors });\n }\n return json.data as TResult;\n }\n}\n\nexport const FetchGraphQLClient = createImplementation({\n abstraction: GraphQLClient,\n implementation: GraphQLClientImpl,\n dependencies: [EventPublisher]\n});\n"],"names":["GraphQLClientImpl","eventPublisher","params","request","RequestValue","body","JSON","endpoint","headers","response","fetch","err","Error","json","publishExtensions","FetchGraphQLClient","createImplementation","GraphQLClient","EventPublisher"],"mappings":";;;;;AAMA,MAAMA;IACF,YAAoBC,cAAwC,CAAE;aAA1CA,cAAc,GAAdA;IAA2C;IAE/D,MAAM,QACFC,MAAyC,EACzB;QAChB,MAAMC,UAAUC,aAAa,IAAI,CAACF;QAElC,MAAMG,OAAOC,KAAK,SAAS,CAAC;YACxB,OAAOH,QAAQ,aAAa;YAC5B,WAAWA,QAAQ,SAAS;YAC5B,eAAeA,QAAQ,aAAa;QACxC;QAEA,OAAO,IAAI,CAAC,KAAK,CAAUA,SAASE;IACxC;IAEA,MAAc,MAAqBF,OAAqB,EAAEE,IAAY,EAAoB;QACtF,MAAME,WAAWJ,QAAQ,QAAQ;QACjC,MAAMK,UAAUL,QAAQ,OAAO;QAC/B,IAAIM;QACJ,IAAI;YACAA,WAAW,MAAMC,MAAMH,UAAU;gBAC7B,QAAQ;gBACR,SAAS;oBACL,gBAAgB;oBAChB,GAAIC,WAAW,CAAC,CAAC;gBACrB;gBACAH;YACJ;QACJ,EAAE,OAAOM,KAAK;YACV,MAAM,IAAIC,MAAM,CAAC,eAAe,EAAGD,IAAc,OAAO,EAAE;QAC9D;QACA,IAAIE;QACJ,IAAI;YACAA,OAAO,MAAMJ,SAAS,IAAI;QAC9B,EAAE,OAAM;YACJ,MAAM,IAAIG,MAAM;QACpB;QAGA,IAAIH,AAAoB,QAApBA,SAAS,MAAM,EACf,MAAM;YAAE,SAASI,KAAK,OAAO;YAAE,MAAMA,KAAK,IAAI;QAAC;QAQnD,MAAMC,kBAAkB,IAAI,CAAC,cAAc,EAAE;YACzCP;YACA,eAAeJ,QAAQ,aAAa;YACpC,YAAYU,KAAK,UAAU;QAC/B;QAQA,IAAIA,KAAK,MAAM,IAAIA,KAAK,MAAM,CAAC,MAAM,GAAG,KAAK,CAACA,KAAK,IAAI,EACnD,MAAM,IAAID,MAAM,kBAAkB;YAAE,OAAOC,KAAK,MAAM;QAAC;QAE3D,OAAOA,KAAK,IAAI;IACpB;AACJ;AAEO,MAAME,qBAAqBC,qBAAqB;IACnD,aAAaC;IACb,gBAAgBjB;IAChB,cAAc;QAACkB;KAAe;AAClC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { BaseEvent } from "../../features/eventPublisher/index.js";
|
|
2
|
+
export interface GraphQLExtensionsPayload {
|
|
3
|
+
endpoint: string;
|
|
4
|
+
operationName?: string;
|
|
5
|
+
extensions: Record<string, any>;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Published when a GraphQL response carries `extensions`.
|
|
9
|
+
*
|
|
10
|
+
* `execute` returns only `data`, so extensions would otherwise be unreachable to anything outside
|
|
11
|
+
* this client: a decorator sees the return value, which is already past them. Publishing keeps that
|
|
12
|
+
* contract intact while letting an interested feature observe them, without this package needing to
|
|
13
|
+
* know who is listening.
|
|
14
|
+
*/
|
|
15
|
+
export declare class GraphQLExtensionsEvent extends BaseEvent<GraphQLExtensionsPayload> {
|
|
16
|
+
eventType: "graphql.extensions";
|
|
17
|
+
getHandlerAbstraction(): import("@webiny/di").Abstraction<import("~/features/eventPublisher/index.js").IEventHandler<GraphQLExtensionsEvent>>;
|
|
18
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { BaseEvent } from "../eventPublisher/index.js";
|
|
2
|
+
import { GraphQLExtensionsEventHandler } from "./abstractions.js";
|
|
3
|
+
class GraphQLExtensionsEvent extends BaseEvent {
|
|
4
|
+
getHandlerAbstraction() {
|
|
5
|
+
return GraphQLExtensionsEventHandler;
|
|
6
|
+
}
|
|
7
|
+
constructor(...args){
|
|
8
|
+
super(...args), this.eventType = "graphql.extensions";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export { GraphQLExtensionsEvent };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=GraphQLExtensionsEvent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/graphqlClient/GraphQLExtensionsEvent.js","sources":["../../../src/features/graphqlClient/GraphQLExtensionsEvent.ts"],"sourcesContent":["import { BaseEvent } from \"~/features/eventPublisher/index.js\";\nimport { GraphQLExtensionsEventHandler } from \"./abstractions.js\";\n\nexport interface GraphQLExtensionsPayload {\n endpoint: string;\n operationName?: string;\n extensions: Record<string, any>;\n}\n\n/**\n * Published when a GraphQL response carries `extensions`.\n *\n * `execute` returns only `data`, so extensions would otherwise be unreachable to anything outside\n * this client: a decorator sees the return value, which is already past them. Publishing keeps that\n * contract intact while letting an interested feature observe them, without this package needing to\n * know who is listening.\n */\nexport class GraphQLExtensionsEvent extends BaseEvent<GraphQLExtensionsPayload> {\n eventType = \"graphql.extensions\" as const;\n\n getHandlerAbstraction() {\n return GraphQLExtensionsEventHandler;\n }\n}\n"],"names":["GraphQLExtensionsEvent","BaseEvent","GraphQLExtensionsEventHandler"],"mappings":";;AAiBO,MAAMA,+BAA+BC;IAGxC,wBAAwB;QACpB,OAAOC;IACX;;QALG,qBACH,SAAS,GAAG;;AAKhB"}
|
|
@@ -5,6 +5,8 @@ import { FetchGraphQLClient } from "../FetchGraphQLClient.js";
|
|
|
5
5
|
import { BatchingGraphQLClient } from "../BatchingGraphQLClient.js";
|
|
6
6
|
import { RetryGraphQLClient } from "../RetryGraphQLClient.js";
|
|
7
7
|
import { EnvConfig } from "../../envConfig/index.js";
|
|
8
|
+
import { EventPublisher } from "../../eventPublisher/index.js";
|
|
9
|
+
import { GraphQLExtensionsEvent } from "../GraphQLExtensionsEvent.js";
|
|
8
10
|
import { __webpack_require__ } from "../../../rslib-runtime.js";
|
|
9
11
|
describe("GraphQLClient Feature", ()=>{
|
|
10
12
|
let container;
|
|
@@ -17,6 +19,9 @@ describe("GraphQLClient Feature", ()=>{
|
|
|
17
19
|
})
|
|
18
20
|
};
|
|
19
21
|
container.registerInstance(EnvConfig, mockEnvConfig);
|
|
22
|
+
container.registerInstance(EventPublisher, {
|
|
23
|
+
publish: vi.fn(async ()=>void 0)
|
|
24
|
+
});
|
|
20
25
|
});
|
|
21
26
|
describe("FetchGraphQLClient", ()=>{
|
|
22
27
|
beforeEach(()=>{
|
|
@@ -48,6 +53,83 @@ describe("GraphQLClient Feature", ()=>{
|
|
|
48
53
|
}
|
|
49
54
|
}));
|
|
50
55
|
});
|
|
56
|
+
it("should publish the response's extensions", async ()=>{
|
|
57
|
+
const extensions = {
|
|
58
|
+
debug: {
|
|
59
|
+
enabled: true,
|
|
60
|
+
entries: []
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
64
|
+
status: 200,
|
|
65
|
+
json: async ()=>({
|
|
66
|
+
data: {
|
|
67
|
+
user: null
|
|
68
|
+
},
|
|
69
|
+
extensions
|
|
70
|
+
})
|
|
71
|
+
});
|
|
72
|
+
const client = container.resolve(GraphQLClient);
|
|
73
|
+
const result = await client.execute({
|
|
74
|
+
endpoint: "https://api.example.com/graphql",
|
|
75
|
+
query: "query GetUser { user { id } }"
|
|
76
|
+
});
|
|
77
|
+
expect(result).toEqual({
|
|
78
|
+
user: null
|
|
79
|
+
});
|
|
80
|
+
const publish = vi.mocked(container.resolve(EventPublisher).publish);
|
|
81
|
+
expect(publish).toHaveBeenCalledTimes(1);
|
|
82
|
+
const event = publish.mock.calls[0][0];
|
|
83
|
+
expect(event).toBeInstanceOf(GraphQLExtensionsEvent);
|
|
84
|
+
expect(event.payload).toEqual({
|
|
85
|
+
endpoint: "https://api.example.com/graphql",
|
|
86
|
+
operationName: "GetUser",
|
|
87
|
+
extensions
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
it("should publish extensions even when the operation failed", async ()=>{
|
|
91
|
+
const extensions = {
|
|
92
|
+
debug: {
|
|
93
|
+
enabled: true,
|
|
94
|
+
entries: []
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
98
|
+
status: 200,
|
|
99
|
+
json: async ()=>({
|
|
100
|
+
errors: [
|
|
101
|
+
{
|
|
102
|
+
message: "Boom"
|
|
103
|
+
}
|
|
104
|
+
],
|
|
105
|
+
extensions
|
|
106
|
+
})
|
|
107
|
+
});
|
|
108
|
+
const client = container.resolve(GraphQLClient);
|
|
109
|
+
await expect(client.execute({
|
|
110
|
+
endpoint: "https://api.example.com/graphql",
|
|
111
|
+
query: "query GetUser { user { id } }"
|
|
112
|
+
})).rejects.toThrow("GraphQL errors");
|
|
113
|
+
const publish = vi.mocked(container.resolve(EventPublisher).publish);
|
|
114
|
+
expect(publish).toHaveBeenCalledTimes(1);
|
|
115
|
+
expect(publish.mock.calls[0][0].payload.extensions).toEqual(extensions);
|
|
116
|
+
});
|
|
117
|
+
it("should publish nothing when the response has no extensions", async ()=>{
|
|
118
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
119
|
+
status: 200,
|
|
120
|
+
json: async ()=>({
|
|
121
|
+
data: {
|
|
122
|
+
user: null
|
|
123
|
+
}
|
|
124
|
+
})
|
|
125
|
+
});
|
|
126
|
+
const client = container.resolve(GraphQLClient);
|
|
127
|
+
await client.execute({
|
|
128
|
+
endpoint: "https://api.example.com/graphql",
|
|
129
|
+
query: "query GetUser { user { id } }"
|
|
130
|
+
});
|
|
131
|
+
expect(container.resolve(EventPublisher).publish).not.toHaveBeenCalled();
|
|
132
|
+
});
|
|
51
133
|
it("should execute a mutation successfully", async ()=>{
|
|
52
134
|
const mockResponse = {
|
|
53
135
|
data: {
|
|
@@ -127,6 +209,37 @@ describe("GraphQLClient Feature", ()=>{
|
|
|
127
209
|
query: "query { user { id } }"
|
|
128
210
|
})).rejects.toThrow("GraphQL errors");
|
|
129
211
|
});
|
|
212
|
+
it("should return partial data when the response carries both data and errors", async ()=>{
|
|
213
|
+
const mockResponse = {
|
|
214
|
+
data: {
|
|
215
|
+
content: {
|
|
216
|
+
data: [
|
|
217
|
+
{
|
|
218
|
+
id: "1"
|
|
219
|
+
},
|
|
220
|
+
{
|
|
221
|
+
id: "2"
|
|
222
|
+
}
|
|
223
|
+
]
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
errors: [
|
|
227
|
+
{
|
|
228
|
+
message: "Cannot return null for non-nullable field RefField.id."
|
|
229
|
+
}
|
|
230
|
+
]
|
|
231
|
+
};
|
|
232
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
233
|
+
status: 200,
|
|
234
|
+
json: async ()=>mockResponse
|
|
235
|
+
});
|
|
236
|
+
const client = container.resolve(GraphQLClient);
|
|
237
|
+
const result = await client.execute({
|
|
238
|
+
endpoint: "https://api.example.com/graphql",
|
|
239
|
+
query: "query { content { data { id } } }"
|
|
240
|
+
});
|
|
241
|
+
expect(result).toEqual(mockResponse.data);
|
|
242
|
+
});
|
|
130
243
|
it("should throw on invalid JSON response", async ()=>{
|
|
131
244
|
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
132
245
|
json: async ()=>{
|
|
@@ -184,6 +297,52 @@ describe("GraphQLClient Feature", ()=>{
|
|
|
184
297
|
const callBody = JSON.parse(__webpack_require__.g.fetch.mock.calls[0][1].body);
|
|
185
298
|
expect(callBody).toHaveLength(2);
|
|
186
299
|
});
|
|
300
|
+
it("should publish the extensions of a batched response", async ()=>{
|
|
301
|
+
const extensions = {
|
|
302
|
+
debug: {
|
|
303
|
+
enabled: true,
|
|
304
|
+
entries: []
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
const mockResponse = [
|
|
308
|
+
{
|
|
309
|
+
data: {
|
|
310
|
+
user: {
|
|
311
|
+
id: "1"
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
},
|
|
315
|
+
{
|
|
316
|
+
data: {
|
|
317
|
+
post: {
|
|
318
|
+
id: "2"
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
extensions
|
|
322
|
+
}
|
|
323
|
+
];
|
|
324
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
325
|
+
json: async ()=>mockResponse
|
|
326
|
+
});
|
|
327
|
+
const client = container.resolve(GraphQLClient);
|
|
328
|
+
await Promise.all([
|
|
329
|
+
client.execute({
|
|
330
|
+
endpoint: "https://api.example.com/graphql",
|
|
331
|
+
query: "query GetUser { user { id } }"
|
|
332
|
+
}),
|
|
333
|
+
client.execute({
|
|
334
|
+
endpoint: "https://api.example.com/graphql",
|
|
335
|
+
query: "query GetPost { post { id } }"
|
|
336
|
+
})
|
|
337
|
+
]);
|
|
338
|
+
const publish = vi.mocked(container.resolve(EventPublisher).publish);
|
|
339
|
+
expect(publish).toHaveBeenCalledTimes(1);
|
|
340
|
+
expect(publish.mock.calls[0][0].payload).toEqual({
|
|
341
|
+
endpoint: "https://api.example.com/graphql",
|
|
342
|
+
operationName: "GetPost",
|
|
343
|
+
extensions
|
|
344
|
+
});
|
|
345
|
+
});
|
|
187
346
|
it("should execute single request without batching", async ()=>{
|
|
188
347
|
const mockResponse = {
|
|
189
348
|
data: {
|
|
@@ -293,6 +452,49 @@ describe("GraphQLClient Feature", ()=>{
|
|
|
293
452
|
];
|
|
294
453
|
await expect(Promise.all(promises)).rejects.toThrow("GraphQL errors in operation 1");
|
|
295
454
|
});
|
|
455
|
+
it("should return partial data for a batched operation that has data and errors", async ()=>{
|
|
456
|
+
const mockResponse = [
|
|
457
|
+
{
|
|
458
|
+
data: {
|
|
459
|
+
user: {
|
|
460
|
+
id: "1"
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
{
|
|
465
|
+
data: {
|
|
466
|
+
content: {
|
|
467
|
+
data: [
|
|
468
|
+
{
|
|
469
|
+
id: "2"
|
|
470
|
+
}
|
|
471
|
+
]
|
|
472
|
+
}
|
|
473
|
+
},
|
|
474
|
+
errors: [
|
|
475
|
+
{
|
|
476
|
+
message: "Cannot return null for non-nullable field RefField.id."
|
|
477
|
+
}
|
|
478
|
+
]
|
|
479
|
+
}
|
|
480
|
+
];
|
|
481
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
482
|
+
json: async ()=>mockResponse
|
|
483
|
+
});
|
|
484
|
+
const client = container.resolve(GraphQLClient);
|
|
485
|
+
const [result1, result2] = await Promise.all([
|
|
486
|
+
client.execute({
|
|
487
|
+
endpoint: "https://api.example.com/graphql",
|
|
488
|
+
query: "query { user { id } }"
|
|
489
|
+
}),
|
|
490
|
+
client.execute({
|
|
491
|
+
endpoint: "https://api.example.com/graphql",
|
|
492
|
+
query: "query { content { data { id } } }"
|
|
493
|
+
})
|
|
494
|
+
]);
|
|
495
|
+
expect(result1).toEqual(mockResponse[0].data);
|
|
496
|
+
expect(result2).toEqual(mockResponse[1].data);
|
|
497
|
+
});
|
|
296
498
|
});
|
|
297
499
|
describe("RetryGraphQLClient", ()=>{
|
|
298
500
|
beforeEach(()=>{
|