@webiny/app 6.6.0-alpha.0 → 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 +3 -0
- package/exports/admin.js +3 -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/apiStreamClient/FetchApiStreamClient.d.ts +9 -0
- package/features/apiStreamClient/FetchApiStreamClient.js +63 -0
- package/features/apiStreamClient/FetchApiStreamClient.js.map +1 -0
- package/features/apiStreamClient/__tests__/FetchApiStreamClient.test.d.ts +1 -0
- package/features/apiStreamClient/__tests__/FetchApiStreamClient.test.js +170 -0
- package/features/apiStreamClient/__tests__/FetchApiStreamClient.test.js.map +1 -0
- package/features/apiStreamClient/__tests__/readServerSentEvents.test.d.ts +1 -0
- package/features/apiStreamClient/__tests__/readServerSentEvents.test.js +160 -0
- package/features/apiStreamClient/__tests__/readServerSentEvents.test.js.map +1 -0
- package/features/apiStreamClient/abstractions.d.ts +44 -0
- package/features/apiStreamClient/abstractions.js +10 -0
- package/features/apiStreamClient/abstractions.js.map +1 -0
- package/features/apiStreamClient/feature.d.ts +3 -0
- package/features/apiStreamClient/feature.js +17 -0
- package/features/apiStreamClient/feature.js.map +1 -0
- package/features/apiStreamClient/index.d.ts +5 -0
- package/features/apiStreamClient/index.js +5 -0
- package/features/apiStreamClient/readServerSentEvents.d.ts +10 -0
- package/features/apiStreamClient/readServerSentEvents.js +29 -0
- package/features/apiStreamClient/readServerSentEvents.js.map +1 -0
- package/features/apiStreamClient/toPayloadHash.d.ts +14 -0
- package/features/apiStreamClient/toPayloadHash.js +7 -0
- package/features/apiStreamClient/toPayloadHash.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,17 @@
|
|
|
1
|
+
import { ApiStreamClient } from "./abstractions.js";
|
|
2
|
+
import { FetchApiStreamClient } from "./FetchApiStreamClient.js";
|
|
3
|
+
import { createFeature } from "../../shared/di/createFeature.js";
|
|
4
|
+
const ApiStreamClientFeature = createFeature({
|
|
5
|
+
name: "ApiStreamClient",
|
|
6
|
+
register (container) {
|
|
7
|
+
container.register(FetchApiStreamClient).inSingletonScope();
|
|
8
|
+
},
|
|
9
|
+
resolve (container) {
|
|
10
|
+
return {
|
|
11
|
+
client: container.resolve(ApiStreamClient)
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
export { ApiStreamClientFeature };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=feature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiStreamClient/feature.js","sources":["../../../src/features/apiStreamClient/feature.ts"],"sourcesContent":["import { ApiStreamClient } from \"./abstractions.js\";\nimport { FetchApiStreamClient } from \"./FetchApiStreamClient.js\";\nimport { createFeature } from \"~/shared/di/createFeature.js\";\n\nexport const ApiStreamClientFeature = createFeature({\n name: \"ApiStreamClient\",\n register(container) {\n container.register(FetchApiStreamClient).inSingletonScope();\n },\n resolve(container) {\n return {\n client: container.resolve(ApiStreamClient)\n };\n }\n});\n"],"names":["ApiStreamClientFeature","createFeature","container","FetchApiStreamClient","ApiStreamClient"],"mappings":";;;AAIO,MAAMA,yBAAyBC,cAAc;IAChD,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC,sBAAsB,gBAAgB;IAC7D;IACA,SAAQD,SAAS;QACb,OAAO;YACH,QAAQA,UAAU,OAAO,CAACE;QAC9B;IACJ;AACJ"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read a `text/event-stream` response as a sequence of parsed JSON events.
|
|
3
|
+
*
|
|
4
|
+
* Written against `Response.body` rather than `EventSource` on purpose: `EventSource` can only issue
|
|
5
|
+
* GET requests and cannot set an `Authorization` header, both of which the API requires.
|
|
6
|
+
*
|
|
7
|
+
* Only the `data:` field is interpreted — enough for Webiny's streaming routes, which frame one JSON
|
|
8
|
+
* object per record. Comment lines (`:` heartbeats), `event:`, `id:` and `retry:` are ignored.
|
|
9
|
+
*/
|
|
10
|
+
export declare function readServerSentEvents<TEvent>(response: Response): AsyncGenerator<TEvent>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
async function* readServerSentEvents(response) {
|
|
2
|
+
const body = response.body;
|
|
3
|
+
if (!body) throw new Error("The response carried no readable body.");
|
|
4
|
+
const reader = body.getReader();
|
|
5
|
+
const decoder = new TextDecoder();
|
|
6
|
+
let buffer = "";
|
|
7
|
+
try {
|
|
8
|
+
while(true){
|
|
9
|
+
const { done, value } = await reader.read();
|
|
10
|
+
if (done) break;
|
|
11
|
+
buffer += decoder.decode(value, {
|
|
12
|
+
stream: true
|
|
13
|
+
}).replace(/\r\n/g, "\n");
|
|
14
|
+
let separator = buffer.indexOf("\n\n");
|
|
15
|
+
while(-1 !== separator){
|
|
16
|
+
const record = buffer.slice(0, separator);
|
|
17
|
+
buffer = buffer.slice(separator + 2);
|
|
18
|
+
const data = record.split("\n").filter((line)=>line.startsWith("data:")).map((line)=>line.slice(5).trim()).join("\n");
|
|
19
|
+
if (data) yield JSON.parse(data);
|
|
20
|
+
separator = buffer.indexOf("\n\n");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
} finally{
|
|
24
|
+
reader.releaseLock();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export { readServerSentEvents };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=readServerSentEvents.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiStreamClient/readServerSentEvents.js","sources":["../../../src/features/apiStreamClient/readServerSentEvents.ts"],"sourcesContent":["/**\n * Read a `text/event-stream` response as a sequence of parsed JSON events.\n *\n * Written against `Response.body` rather than `EventSource` on purpose: `EventSource` can only issue\n * GET requests and cannot set an `Authorization` header, both of which the API requires.\n *\n * Only the `data:` field is interpreted — enough for Webiny's streaming routes, which frame one JSON\n * object per record. Comment lines (`:` heartbeats), `event:`, `id:` and `retry:` are ignored.\n */\nexport async function* readServerSentEvents<TEvent>(response: Response): AsyncGenerator<TEvent> {\n const body = response.body;\n if (!body) {\n throw new Error(\"The response carried no readable body.\");\n }\n\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n // `stream: true` keeps a multi-byte character split across chunks intact.\n buffer += decoder.decode(value, { stream: true }).replace(/\\r\\n/g, \"\\n\");\n\n let separator = buffer.indexOf(\"\\n\\n\");\n while (separator !== -1) {\n const record = buffer.slice(0, separator);\n buffer = buffer.slice(separator + 2);\n\n const data = record\n .split(\"\\n\")\n .filter(line => line.startsWith(\"data:\"))\n .map(line => line.slice(\"data:\".length).trim())\n .join(\"\\n\");\n\n if (data) {\n yield JSON.parse(data) as TEvent;\n }\n\n separator = buffer.indexOf(\"\\n\\n\");\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n"],"names":["readServerSentEvents","response","body","Error","reader","decoder","TextDecoder","buffer","done","value","separator","record","data","line","JSON"],"mappings":"AASO,gBAAgBA,qBAA6BC,QAAkB;IAClE,MAAMC,OAAOD,SAAS,IAAI;IAC1B,IAAI,CAACC,MACD,MAAM,IAAIC,MAAM;IAGpB,MAAMC,SAASF,KAAK,SAAS;IAC7B,MAAMG,UAAU,IAAIC;IACpB,IAAIC,SAAS;IAEb,IAAI;QACA,MAAO,KAAM;YACT,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAML,OAAO,IAAI;YAEzC,IAAII,MACA;YAIJD,UAAUF,QAAQ,MAAM,CAACI,OAAO;gBAAE,QAAQ;YAAK,GAAG,OAAO,CAAC,SAAS;YAEnE,IAAIC,YAAYH,OAAO,OAAO,CAAC;YAC/B,MAAOG,AAAc,OAAdA,UAAkB;gBACrB,MAAMC,SAASJ,OAAO,KAAK,CAAC,GAAGG;gBAC/BH,SAASA,OAAO,KAAK,CAACG,YAAY;gBAElC,MAAME,OAAOD,OACR,KAAK,CAAC,MACN,MAAM,CAACE,CAAAA,OAAQA,KAAK,UAAU,CAAC,UAC/B,GAAG,CAACA,CAAAA,OAAQA,KAAK,KAAK,CAAC,GAAgB,IAAI,IAC3C,IAAI,CAAC;gBAEV,IAAID,MACA,MAAME,KAAK,KAAK,CAACF;gBAGrBF,YAAYH,OAAO,OAAO,CAAC;YAC/B;QACJ;IACJ,SAAU;QACNH,OAAO,WAAW;IACtB;AACJ"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hex SHA-256 of a request body, for the `x-amz-content-sha256` header.
|
|
3
|
+
*
|
|
4
|
+
* Required whenever a streaming route is reached through CloudFront with Origin Access Control. OAC
|
|
5
|
+
* signs the request with SigV4 but does NOT hash the body itself — it folds whatever this header says
|
|
6
|
+
* into the signature, and the Lambda Function URL's IAM authorizer then recomputes the hash from the
|
|
7
|
+
* body it received. Omit the header and the two disagree, so a POST WITH a body is rejected with
|
|
8
|
+
* `InvalidSignatureException` while a bodyless POST succeeds, because an empty payload hashes
|
|
9
|
+
* predictably.
|
|
10
|
+
*
|
|
11
|
+
* `crypto.subtle` needs a secure context, which the streaming behavior already requires
|
|
12
|
+
* (`viewerProtocolPolicy: "https-only"`).
|
|
13
|
+
*/
|
|
14
|
+
export declare function toPayloadHash(body: string): Promise<string>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
async function toPayloadHash(body) {
|
|
2
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body));
|
|
3
|
+
return Array.from(new Uint8Array(digest)).map((byte)=>byte.toString(16).padStart(2, "0")).join("");
|
|
4
|
+
}
|
|
5
|
+
export { toPayloadHash };
|
|
6
|
+
|
|
7
|
+
//# sourceMappingURL=toPayloadHash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiStreamClient/toPayloadHash.js","sources":["../../../src/features/apiStreamClient/toPayloadHash.ts"],"sourcesContent":["/**\n * Hex SHA-256 of a request body, for the `x-amz-content-sha256` header.\n *\n * Required whenever a streaming route is reached through CloudFront with Origin Access Control. OAC\n * signs the request with SigV4 but does NOT hash the body itself — it folds whatever this header says\n * into the signature, and the Lambda Function URL's IAM authorizer then recomputes the hash from the\n * body it received. Omit the header and the two disagree, so a POST WITH a body is rejected with\n * `InvalidSignatureException` while a bodyless POST succeeds, because an empty payload hashes\n * predictably.\n *\n * `crypto.subtle` needs a secure context, which the streaming behavior already requires\n * (`viewerProtocolPolicy: \"https-only\"`).\n */\nexport async function toPayloadHash(body: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(body));\n\n return Array.from(new Uint8Array(digest))\n .map(byte => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n"],"names":["toPayloadHash","body","digest","crypto","TextEncoder","Array","Uint8Array","byte"],"mappings":"AAaO,eAAeA,cAAcC,IAAY;IAC5C,MAAMC,SAAS,MAAMC,OAAO,MAAM,CAAC,MAAM,CAAC,WAAW,IAAIC,cAAc,MAAM,CAACH;IAE9E,OAAOI,MAAM,IAAI,CAAC,IAAIC,WAAWJ,SAC5B,GAAG,CAACK,CAAAA,OAAQA,KAAK,QAAQ,CAAC,IAAI,QAAQ,CAAC,GAAG,MAC1C,IAAI,CAAC;AACd"}
|
|
@@ -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"],"mapp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raphQLClient.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,IAAI,CAAC,KAAK;YAId,IAAI,CAAC,IAAI,CAAC,YAAY,EAClB,IAAI,CAAC,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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(()=>{
|