@avantstay/graphql-ts-client 11.0.0 → 12.0.1

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/README.md CHANGED
@@ -33,10 +33,10 @@ import { myAwesomeApi, AssetType, Granularity, OnBoardingStage } from './myAweso
33
33
  async function somewhereOverTheRainbow() {
34
34
  // Set an specific header if needed
35
35
  myAwesomeApi.setHeader('Authorization', 'Bearer 010101010101')
36
-
36
+
37
37
  // You can also change the API url
38
38
  myAwesomeApi.setUrl('https://my-runtime-url.com/graphql')
39
-
39
+
40
40
  // And configure how retrials should work
41
41
  myAwesomeApi.setRetryConfig({
42
42
  max: 3,
@@ -44,12 +44,12 @@ async function somewhereOverTheRainbow() {
44
44
  // do something before retrying
45
45
  },
46
46
  })
47
-
47
+
48
48
  // Adding response listeners is also possible
49
49
  myAwesomeApi.addResponseListener(({ queryName, query, variables, response }) => {
50
50
  // do something whenever a request is responded
51
51
  })
52
-
52
+
53
53
  const response = await myAwesomeApi.queries.globalIndicators({
54
54
  // Optionally you can define an alias for this request
55
55
  __alias: 'myCustomGlobalIndicators',
@@ -0,0 +1,18 @@
1
+ // src/types.ts
2
+ var GraphQLClientError = class extends Error {
3
+ constructor(responseData) {
4
+ super();
5
+ this.responseData = responseData;
6
+ Object.setPrototypeOf(this, GraphQLClientError.prototype);
7
+ }
8
+ get message() {
9
+ return this.response.errors.map((it) => it.message).join(";\n");
10
+ }
11
+ get response() {
12
+ return this.responseData;
13
+ }
14
+ };
15
+
16
+ export {
17
+ GraphQLClientError
18
+ };
@@ -0,0 +1,27 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw new Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/types.ts
10
+ var GraphQLClientError = class extends Error {
11
+ constructor(responseData) {
12
+ super();
13
+ this.responseData = responseData;
14
+ Object.setPrototypeOf(this, GraphQLClientError.prototype);
15
+ }
16
+ get message() {
17
+ return this.response.errors.map((it) => it.message).join(";\n");
18
+ }
19
+ get response() {
20
+ return this.responseData;
21
+ }
22
+ };
23
+
24
+ export {
25
+ __require,
26
+ GraphQLClientError
27
+ };
@@ -1,4 +1,4 @@
1
- import { C as ClientConfig, I as IResponseListener, E as Endpoint } from './types-4ada662b.js';
1
+ import { C as ClientConfig, I as IResponseListener, E as Endpoint } from './types-23d2d6aa.js';
2
2
 
3
3
  declare const getApiEndpointCreator: (apiConfig: {
4
4
  getClient: () => ClientConfig;
package/dist/endpoint.js CHANGED
@@ -591,17 +591,14 @@ function _graphqlRequest() {
591
591
  return _graphqlRequest.apply(this, arguments);
592
592
  }
593
593
  // src/jsonToGraphQLQuery.ts
594
- var import_omit = __toESM(require("lodash/omit"));
594
+ var import_lodash = require("lodash");
595
595
  var VAR_PREFIX = "@@VAR@@";
596
596
  var VAR_PREFIX_LENGTH = VAR_PREFIX.length;
597
- var fromEntries = require("lodash/fromPairs");
598
- var entries = require("lodash/toPairs");
599
- var cloneDeep = require("lodash/cloneDeep");
600
597
  function jsonToGraphQLQuery(param) {
601
598
  var kind = param.kind, queryName = param.queryName, _param_jsonQuery = param.jsonQuery, jsonQuery = _param_jsonQuery === void 0 ? {} : _param_jsonQuery, typesTree = param.typesTree;
602
599
  var variablesData = {};
603
600
  var alias = jsonQuery.__alias;
604
- var newJsonQuery = cloneDeep((0, import_omit.default)(jsonQuery, [
601
+ var newJsonQuery = (0, import_lodash.cloneDeep)((0, import_lodash.omit)(jsonQuery, [
605
602
  "__alias",
606
603
  "__headers",
607
604
  "__url"
@@ -621,12 +618,12 @@ function jsonToGraphQLQuery(param) {
621
618
  });
622
619
  return variablesObj;
623
620
  }, {});
624
- var variablesQuery = Object.keys(variableItems).length ? "(".concat(entries(variableItems).map(function(param) {
621
+ var variablesQuery = Object.keys(variableItems).length ? "(".concat((0, import_lodash.toPairs)(variableItems).map(function(param) {
625
622
  var _param = _slicedToArray(param, 2), queryName2 = _param[0], type = _param[1].type;
626
623
  return "$".concat(queryName2, ": ").concat(type);
627
624
  }).join(", "), ")") : "";
628
625
  var query = "".concat(kind, " ").concat(alias || queryName).concat(variablesQuery, " { ").concat(alias ? "".concat(alias, ":") : "").concat(queryName).concat(toGraphql(newJsonQuery), " }");
629
- var variables = fromEntries(entries(variableItems).map(function(param) {
626
+ var variables = (0, import_lodash.fromPairs)((0, import_lodash.toPairs)(variableItems).map(function(param) {
630
627
  var _param = _slicedToArray(param, 2), k = _param[0], v = _param[1];
631
628
  return [
632
629
  k,
@@ -673,14 +670,14 @@ function extractVariables(param) {
673
670
  });
674
671
  }
675
672
  function toGraphql(jsonQuery) {
676
- var fields = entries(jsonQuery).filter(function(param) {
673
+ var fields = (0, import_lodash.toPairs)(jsonQuery).filter(function(param) {
677
674
  var _param = _slicedToArray(param, 2), k = _param[0], v = _param[1];
678
675
  return k !== "__args" && v !== false && v !== void 0;
679
676
  }).map(function(param) {
680
677
  var _param = _slicedToArray(param, 2), k = _param[0], v = _param[1];
681
678
  return typeof v === "object" ? "".concat(k).concat(toGraphql(v)) : k;
682
679
  }).join(" ");
683
- var validArgs = jsonQuery.__args ? entries(jsonQuery.__args).filter(function(param) {
680
+ var validArgs = jsonQuery.__args ? (0, import_lodash.toPairs)(jsonQuery.__args).filter(function(param) {
684
681
  var _param = _slicedToArray(param, 2), _ = _param[0], v = _param[1];
685
682
  return v !== void 0;
686
683
  }) : [];
@@ -0,0 +1,271 @@
1
+ import {
2
+ GraphQLClientError
3
+ } from "./chunk-2VJ7JZPA.mjs";
4
+
5
+ // src/endpoint.ts
6
+ import memoize from "moize";
7
+
8
+ // src/graphqlRequest.ts
9
+ import _axios from "axios";
10
+ var sleep = (ms = 0) => new Promise((resolve) => {
11
+ setTimeout(() => resolve(), ms);
12
+ });
13
+ async function graphqlRequest({
14
+ shouldRetry = true,
15
+ axios = _axios,
16
+ queryName,
17
+ client,
18
+ query,
19
+ requestHeaders = {},
20
+ variables,
21
+ failureMode,
22
+ errorsParser
23
+ }) {
24
+ let lastResponse;
25
+ const maxRetrials = shouldRetry ? client.retryConfig.max : 0;
26
+ for (let trial = 0; true; trial++) {
27
+ const infoParams = {
28
+ _q: queryName,
29
+ ...trial > 0 ? { _retrial: trial + 1 } : {}
30
+ };
31
+ const {
32
+ data: responseData = {},
33
+ headers,
34
+ status
35
+ } = await axios.post(
36
+ client.url,
37
+ { query, variables, operationName: queryName },
38
+ {
39
+ params: infoParams,
40
+ headers: {
41
+ "Content-Type": "application/json",
42
+ ...client.headers,
43
+ ...requestHeaders
44
+ },
45
+ validateStatus: () => true
46
+ }
47
+ );
48
+ let { data, errors, warnings } = responseData;
49
+ if (status >= 400 && !errors?.length) {
50
+ errors = [{ message: `Request "${queryName}" failed with status ${status}` }];
51
+ }
52
+ lastResponse = {
53
+ errors: errorsParser ? errorsParser(errors) : errors,
54
+ data,
55
+ warnings,
56
+ headers,
57
+ status
58
+ };
59
+ if (!errors?.length) {
60
+ break;
61
+ } else if (trial < maxRetrials && typeof client.retryConfig?.before === "function") {
62
+ await client.retryConfig?.before({
63
+ queryName,
64
+ query,
65
+ variables,
66
+ response: lastResponse
67
+ });
68
+ if (client.retryConfig.waitBeforeRetry) {
69
+ await sleep(client.retryConfig.waitBeforeRetry);
70
+ }
71
+ } else if (trial >= maxRetrials) {
72
+ break;
73
+ }
74
+ }
75
+ if (failureMode === "loud" && lastResponse.errors && lastResponse.errors?.length) {
76
+ throw new GraphQLClientError(lastResponse);
77
+ }
78
+ return lastResponse;
79
+ }
80
+
81
+ // src/jsonToGraphQLQuery.ts
82
+ import { cloneDeep, fromPairs as fromEntries, omit, toPairs as entries } from "lodash";
83
+ var VAR_PREFIX = "@@VAR@@";
84
+ var VAR_PREFIX_LENGTH = VAR_PREFIX.length;
85
+ function jsonToGraphQLQuery({
86
+ kind,
87
+ queryName,
88
+ jsonQuery = {},
89
+ typesTree
90
+ }) {
91
+ const variablesData = {};
92
+ const alias = jsonQuery.__alias;
93
+ const newJsonQuery = cloneDeep(omit(jsonQuery, ["__alias", "__headers", "__url"]));
94
+ extractVariables({
95
+ jsonQuery: { [queryName]: newJsonQuery },
96
+ variables: variablesData,
97
+ parentType: kind === "query" ? typesTree.Query : typesTree.Mutation
98
+ });
99
+ const variableItems = Object.values(variablesData).reduce(
100
+ (variablesObj, variables2) => {
101
+ variables2.forEach((variable, index) => {
102
+ const name = variable.update(variables2.length > 1 ? index : void 0);
103
+ variablesObj[name] = { type: variable.type, value: variable.value };
104
+ });
105
+ return variablesObj;
106
+ },
107
+ {}
108
+ );
109
+ const variablesQuery = Object.keys(variableItems).length ? `(${entries(variableItems).map(([queryName2, { type }]) => `$${queryName2}: ${type}`).join(", ")})` : "";
110
+ const query = `${kind} ${alias || queryName}${variablesQuery} { ${alias ? `${alias}:` : ""}${queryName}${toGraphql(
111
+ newJsonQuery
112
+ )} }`;
113
+ const variables = fromEntries(entries(variableItems).map(([k, v]) => [k, v.value]));
114
+ return {
115
+ query,
116
+ variables
117
+ };
118
+ }
119
+ function extractVariables({
120
+ jsonQuery,
121
+ variables,
122
+ parentType
123
+ }) {
124
+ if (!parentType)
125
+ return;
126
+ if (jsonQuery.__args) {
127
+ Object.keys(jsonQuery.__args).forEach((k) => {
128
+ if (typeof jsonQuery.__args[k] === "string" && jsonQuery.__args[k].startsWith(VAR_PREFIX))
129
+ return;
130
+ if (jsonQuery.__args[k] === void 0)
131
+ return;
132
+ const variableName = k;
133
+ if (!variables[variableName]) {
134
+ variables[variableName] = [];
135
+ }
136
+ variables[variableName].push({
137
+ name: variableName,
138
+ type: parentType.__args[k],
139
+ value: jsonQuery.__args[k],
140
+ update: (index) => {
141
+ const name = `${variableName}${index !== void 0 ? `_${index}` : ""}`;
142
+ jsonQuery.__args[k] = `${VAR_PREFIX}$${name}`;
143
+ return name;
144
+ }
145
+ });
146
+ jsonQuery.__args[k] = VAR_PREFIX;
147
+ });
148
+ }
149
+ Object.keys(jsonQuery).filter((k) => k !== "__args" && typeof jsonQuery[k] === "object").forEach(
150
+ (k) => extractVariables({
151
+ jsonQuery: jsonQuery[k],
152
+ variables,
153
+ parentType: parentType.hasOwnProperty(k) ? parentType[k] : parentType.__fields ? parentType.__fields[k] : void 0
154
+ })
155
+ );
156
+ }
157
+ function toGraphql(jsonQuery) {
158
+ const fields = entries(jsonQuery).filter(([k, v]) => k !== "__args" && v !== false && v !== void 0).map(([k, v]) => typeof v === "object" ? `${k}${toGraphql(v)}` : k).join(" ");
159
+ const validArgs = jsonQuery.__args ? entries(jsonQuery.__args).filter(([_, v]) => v !== void 0) : [];
160
+ const argsQuery = validArgs.length ? `(${validArgs.map(([k, v]) => `${k}:${v.substr(VAR_PREFIX_LENGTH)}`).join(",")})` : "";
161
+ return `${argsQuery} ${fields ? `{ ${fields} }` : ""}`;
162
+ }
163
+
164
+ // src/logging.ts
165
+ function logRequest(logInfo) {
166
+ let identifier = `%c#graphql-ts-client ${logInfo.kind} ${logInfo.queryName}`;
167
+ let identifierStyles = "color: transparent; font-size: 0px";
168
+ console.groupCollapsed(
169
+ `%c#graphql-ts-client %c${logInfo.kind} %c${logInfo.queryName} %c(${logInfo.duration.toFixed(2)}ms)`,
170
+ "color: #f90",
171
+ "color: #999",
172
+ `color: ${logInfo.response ? "unset" : "#f00"}; font-weight: bold`,
173
+ "color: #999"
174
+ );
175
+ console.groupCollapsed(`%cQuery ${identifier}`, "color: #999", identifierStyles);
176
+ console.log(logInfo.formatGraphQL(logInfo.query) + identifier, identifierStyles);
177
+ console.groupEnd();
178
+ console.groupCollapsed(`%cVariables ${identifier}`, "color: #999", identifierStyles);
179
+ console.log(JSON.stringify(logInfo.variables, null, " ") + identifier, identifierStyles);
180
+ console.groupEnd();
181
+ console.groupCollapsed(`%cTrace ${identifier}`, "color: #999", identifierStyles);
182
+ console.trace(identifier, identifierStyles);
183
+ console.groupEnd();
184
+ if (logInfo.response) {
185
+ console.log("%cResponse".padEnd(15, " ") + identifier, "color: #999", identifierStyles, logInfo.response);
186
+ }
187
+ if (logInfo.error) {
188
+ console.log("%cError".padEnd(15, " ") + identifier, "color: #999", identifierStyles, logInfo.error);
189
+ }
190
+ console.groupEnd();
191
+ }
192
+
193
+ // src/endpoint.ts
194
+ var executeListeners = (listeners, data) => setTimeout(() => listeners.forEach((runResponseListener) => runResponseListener(data)));
195
+ var getApiEndpointCreator = (apiConfig) => (kind, queryName) => {
196
+ const rawEndpoint = async (failureMode, jsonQuery) => {
197
+ const clientConfig = apiConfig.getClient();
198
+ const alias = jsonQuery?.__alias ?? queryName;
199
+ const url = jsonQuery?.__url ?? clientConfig.url;
200
+ const shouldRetry = jsonQuery?.__retry ?? true;
201
+ const requestHeaders = jsonQuery?.__headers ?? {};
202
+ const { query, variables } = jsonToGraphQLQuery({ kind, queryName, jsonQuery, typesTree: apiConfig.typesTree });
203
+ const start = +new Date();
204
+ const logOptions = {
205
+ kind,
206
+ queryName: alias,
207
+ formatGraphQL: apiConfig.formatGraphQL,
208
+ requestHeaders,
209
+ query,
210
+ variables
211
+ };
212
+ const responseListenerData = {
213
+ queryName: alias,
214
+ query: apiConfig.formatGraphQL(query),
215
+ variables
216
+ };
217
+ try {
218
+ const { data, errors, warnings, headers, status } = await graphqlRequest({
219
+ shouldRetry,
220
+ failureMode,
221
+ queryName: alias,
222
+ client: { ...clientConfig, url },
223
+ requestHeaders,
224
+ query,
225
+ variables,
226
+ errorsParser: apiConfig.errorsParser
227
+ });
228
+ const response = { data, warnings, headers, status, errors };
229
+ if (apiConfig.verbose && globalThis.document) {
230
+ logRequest({
231
+ ...logOptions,
232
+ response,
233
+ duration: +new Date() - start
234
+ });
235
+ }
236
+ executeListeners(apiConfig.responseListeners, {
237
+ ...responseListenerData,
238
+ response
239
+ });
240
+ return { data: data?.[alias], errors, warnings, headers, status };
241
+ } catch (error) {
242
+ if (apiConfig.verbose && globalThis.document) {
243
+ logRequest({
244
+ ...logOptions,
245
+ error,
246
+ duration: +new Date() - start
247
+ });
248
+ }
249
+ executeListeners(apiConfig.responseListeners, {
250
+ ...responseListenerData,
251
+ response: error.response
252
+ });
253
+ throw error;
254
+ }
255
+ };
256
+ const endpoint = async (jsonQuery) => {
257
+ const { data } = await rawEndpoint("loud", jsonQuery);
258
+ return data;
259
+ };
260
+ const memoizeeOptions = {
261
+ maxAge: apiConfig.maxAge,
262
+ isSerialized: true
263
+ };
264
+ endpoint.raw = rawEndpoint.bind(null, "silent");
265
+ endpoint.memo = memoize(endpoint, memoizeeOptions);
266
+ endpoint.memoRaw = memoize(endpoint.raw, memoizeeOptions);
267
+ return endpoint;
268
+ };
269
+ export {
270
+ getApiEndpointCreator
271
+ };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { PathLike } from 'fs';
2
- export { C as ClientConfig, c as DeepReplace, D as Defined, E as Endpoint, G as GraphQLClientError, I as IResponseListener, J as JsonOutput, L as LogInfo, M as Maybe, P as Projection, d as RawEndpoint, b as Replacement, R as ResponseData, a as ResponseListenerInfo, U as Unpacked } from './types-4ada662b.js';
2
+ import { T as TypescriptClientOutput } from './types-23d2d6aa.js';
3
+ export { C as ClientConfig, c as DeepReplace, D as Defined, E as Endpoint, G as GraphQLClientError, I as IResponseListener, J as JsonOutput, L as LogInfo, M as Maybe, P as Projection, d as RawEndpoint, b as Replacement, R as ResponseData, a as ResponseListenerInfo, T as TypescriptClientOutput, U as Unpacked } from './types-23d2d6aa.js';
3
4
 
4
5
  type IClientOptions = {
5
6
  output?: PathLike;
@@ -14,11 +15,7 @@ type IClientOptions = {
14
15
  skipCache?: boolean;
15
16
  errorsParser?: (errors: any[]) => any;
16
17
  };
17
- type Client = {
18
- typings: string;
19
- js: string;
20
- };
21
- declare function generateTypescriptClient({ introspectionEndpoint, ...options }: IClientOptions): Promise<Client>;
22
- declare function generateTypescriptClientFromSDL(SDL: string, options: IClientOptions): Client;
18
+ declare function generateTypescriptClient({ introspectionEndpoint, ...options }: IClientOptions): Promise<TypescriptClientOutput>;
19
+ declare function generateTypescriptClientFromSDL(SDL: string, options: IClientOptions): TypescriptClientOutput;
23
20
 
24
21
  export { generateTypescriptClient, generateTypescriptClientFromSDL };