@avantstay/graphql-ts-client 10.6.0 → 10.7.0

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/dist/endpoint.js CHANGED
@@ -610,12 +610,22 @@ function jsonToGraphQLQuery(param) {
610
610
  variables: variablesData,
611
611
  parentType: kind === "query" ? typesTree.Query : typesTree.Mutation
612
612
  });
613
- var variablesQuery = Object.keys(variablesData).length ? "(".concat(entries(variablesData).map(function(param) {
613
+ var variableItems = Object.values(variablesData).reduce(function(variablesObj, variables2) {
614
+ variables2.forEach(function(variable, index) {
615
+ var name = variable.update(variables2.length > 1 ? index : void 0);
616
+ variablesObj[name] = {
617
+ type: variable.type,
618
+ value: variable.value
619
+ };
620
+ });
621
+ return variablesObj;
622
+ }, {});
623
+ var variablesQuery = Object.keys(variableItems).length ? "(".concat(entries(variableItems).map(function(param) {
614
624
  var _param = _slicedToArray(param, 2), queryName2 = _param[0], type = _param[1].type;
615
625
  return "$".concat(queryName2, ": ").concat(type);
616
626
  }).join(", "), ")") : "";
617
627
  var query = "".concat(kind, " ").concat(alias || queryName).concat(variablesQuery, " { ").concat(alias ? "".concat(alias, ":") : "").concat(queryName).concat(toGraphql(newJsonQuery), " }");
618
- var variables = fromEntries(entries(variablesData).map(function(param) {
628
+ var variables = fromEntries(entries(variableItems).map(function(param) {
619
629
  var _param = _slicedToArray(param, 2), k = _param[0], v = _param[1];
620
630
  return [
621
631
  k,
@@ -633,14 +643,22 @@ function extractVariables(param) {
633
643
  if (jsonQuery.__args) {
634
644
  Object.keys(jsonQuery.__args).forEach(function(k) {
635
645
  if (typeof jsonQuery.__args[k] === "string" && jsonQuery.__args[k].startsWith(VAR_PREFIX)) return;
636
- var variableName = "".concat(k, "_").concat(Math.random().toString(36).substr(2, 4));
637
- if (jsonQuery.__args[k] !== void 0) {
638
- variables[variableName] = {
639
- type: parentType.__args[k],
640
- value: jsonQuery.__args[k]
641
- };
642
- jsonQuery.__args[k] = "".concat(VAR_PREFIX, "$").concat(variableName);
646
+ if (jsonQuery.__args[k] === void 0) return;
647
+ var variableName = k;
648
+ if (!variables[variableName]) {
649
+ variables[variableName] = [];
643
650
  }
651
+ variables[variableName].push({
652
+ name: variableName,
653
+ type: parentType.__args[k],
654
+ value: jsonQuery.__args[k],
655
+ update: function(index) {
656
+ var name = "".concat(variableName).concat(index !== void 0 ? "_".concat(index) : "");
657
+ jsonQuery.__args[k] = "".concat(VAR_PREFIX, "$").concat(name);
658
+ return name;
659
+ }
660
+ });
661
+ jsonQuery.__args[k] = VAR_PREFIX;
644
662
  });
645
663
  }
646
664
  Object.keys(jsonQuery).filter(function(k) {
package/dist/index.js CHANGED
@@ -487,7 +487,7 @@ var prettier = __toESM(require("prettier"));
487
487
  // package.json
488
488
  var package_default = {
489
489
  name: "@avantstay/graphql-ts-client",
490
- version: "10.6.0",
490
+ version: "10.7.0",
491
491
  description: "GraphQL Typescript Client Generator",
492
492
  author: "Wellington Guimaraes",
493
493
  license: "MIT",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avantstay/graphql-ts-client",
3
- "version": "10.6.0",
3
+ "version": "10.7.0",
4
4
  "description": "GraphQL Typescript Client Generator",
5
5
  "author": "Wellington Guimaraes",
6
6
  "license": "MIT",
@@ -8,8 +8,8 @@
8
8
  "typings": "dist/index.d.ts",
9
9
  "scripts": {
10
10
  "build": "tsup src/index.ts src/endpoint.ts --dts",
11
- "test": "cross-env GQL_CLIENT_DIST_PATH='.' jest --watch"
12
-
11
+ "test": "cross-env GQL_CLIENT_DIST_PATH='.' jest --watch",
12
+ "prepublishOnly": "yarn build"
13
13
  },
14
14
  "files": [
15
15
  "dist",
@@ -38,8 +38,14 @@ describe('jsonToGraphQLQuery', () => {
38
38
  __args: {
39
39
  foo: 'Bar',
40
40
  },
41
-
42
41
  something: true,
42
+ another: {
43
+ __args: {
44
+ foo: 'Lorem ipsum',
45
+ bar: 'Dolor sit amet',
46
+ },
47
+ zeta: true,
48
+ },
43
49
  }
44
50
 
45
51
  const response = jsonToGraphQLQuery({
@@ -53,14 +59,24 @@ describe('jsonToGraphQLQuery', () => {
53
59
  __args: {
54
60
  foo: 'UUID!',
55
61
  },
62
+ something: 'Boolean!',
63
+ another: {
64
+ __args: {
65
+ foo: 'String!',
66
+ bar: 'String!',
67
+ },
68
+ zeta: 'Int!',
69
+ },
56
70
  }
57
71
  },
58
72
  },
59
73
  },
60
74
  })
61
75
 
62
- Object.keys(response.variables).forEach(varName => {
63
- expect(response.query.split(varName).length - 1).toBeGreaterThanOrEqual(2) //every variable name should be present at least 2 times
76
+ expect(response.variables).toEqual({
77
+ foo_0: 'Bar',
78
+ foo_1: 'Lorem ipsum',
79
+ bar: 'Dolor sit amet',
64
80
  })
65
81
  })
66
82
  })
@@ -7,6 +7,9 @@ const fromEntries: (arr: [string, any][]) => { [key: string]: any } = require('l
7
7
  const entries: (obj: { [key: string]: any }) => [string, any][] = require('lodash/toPairs')
8
8
  const cloneDeep = require('lodash/cloneDeep')
9
9
 
10
+ type ExtractedVariables = Record<string, (Variable & { name: string; update: (index?: number) => string })[]>
11
+ type Variable = { type: any; value: any }
12
+
10
13
  export function jsonToGraphQLQuery({
11
14
  kind,
12
15
  queryName,
@@ -18,7 +21,7 @@ export function jsonToGraphQLQuery({
18
21
  jsonQuery: any
19
22
  typesTree: any
20
23
  }) {
21
- const variablesData = {} as any
24
+ const variablesData = {} as ExtractedVariables
22
25
  const alias = jsonQuery.__alias
23
26
  const newJsonQuery = cloneDeep(omit(jsonQuery, ['__alias', '__headers']))
24
27
 
@@ -28,8 +31,17 @@ export function jsonToGraphQLQuery({
28
31
  parentType: kind === 'query' ? typesTree.Query : typesTree.Mutation,
29
32
  })
30
33
 
31
- const variablesQuery = Object.keys(variablesData).length
32
- ? `(${entries(variablesData)
34
+ const variableItems = Object.values(variablesData).reduce((variablesObj, variables) => {
35
+ variables.forEach((variable, index) => {
36
+ const name = variable.update(variables.length > 1 ? index : undefined)
37
+ variablesObj[name] = { type: variable.type, value: variable.value }
38
+ })
39
+
40
+ return variablesObj
41
+ }, {} as Record<string, Variable>)
42
+
43
+ const variablesQuery = Object.keys(variableItems).length
44
+ ? `(${entries(variableItems)
33
45
  .map(([queryName, { type }]: any) => `$${queryName}: ${type}`)
34
46
  .join(', ')})`
35
47
  : ''
@@ -37,7 +49,7 @@ export function jsonToGraphQLQuery({
37
49
  const query = `${kind} ${alias || queryName}${variablesQuery} { ${alias ? `${alias}:` : ''}${queryName}${toGraphql(
38
50
  newJsonQuery
39
51
  )} }`
40
- const variables = fromEntries(entries(variablesData).map(([k, v]: any) => [k, v.value]))
52
+ const variables = fromEntries(entries(variableItems).map(([k, v]: any) => [k, v.value]))
41
53
 
42
54
  return {
43
55
  query,
@@ -45,22 +57,41 @@ export function jsonToGraphQLQuery({
45
57
  }
46
58
  }
47
59
 
48
- function extractVariables({ jsonQuery, variables, parentType }: { jsonQuery: any; variables: any; parentType: any }) {
60
+ function extractVariables({
61
+ jsonQuery,
62
+ variables,
63
+ parentType,
64
+ }: {
65
+ jsonQuery: any
66
+ variables: ExtractedVariables
67
+ parentType: any
68
+ }) {
49
69
  if (!parentType) return
50
70
 
51
71
  if (jsonQuery.__args) {
52
72
  Object.keys(jsonQuery.__args).forEach(k => {
53
73
  if (typeof jsonQuery.__args[k] === 'string' && jsonQuery.__args[k].startsWith(VAR_PREFIX)) return
74
+ if (jsonQuery.__args[k] === undefined) return
54
75
 
55
- const variableName = `${k}_${Math.random().toString(36).substr(2, 4)}`
76
+ const variableName = k
56
77
 
57
- if (jsonQuery.__args[k] !== undefined) {
58
- variables[variableName] = {
59
- type: parentType.__args[k],
60
- value: jsonQuery.__args[k],
61
- }
62
- jsonQuery.__args[k] = `${VAR_PREFIX}$${variableName}`
78
+ if (!variables[variableName]) {
79
+ variables[variableName] = []
63
80
  }
81
+
82
+ variables[variableName].push({
83
+ name: variableName,
84
+ type: parentType.__args[k],
85
+ value: jsonQuery.__args[k],
86
+ update: (index?: number) => {
87
+ const name = `${variableName}${index !== undefined ? `_${index}` : ''}`
88
+ jsonQuery.__args[k] = `${VAR_PREFIX}$${name}`
89
+
90
+ return name
91
+ },
92
+ })
93
+
94
+ jsonQuery.__args[k] = VAR_PREFIX
64
95
  })
65
96
  }
66
97
 
@@ -1,148 +0,0 @@
1
- // noinspection TypeScriptUnresolvedVariable, ES6UnusedImports, JSUnusedLocalSymbols, TypeScriptCheckImport
2
- import { DeepRequired } from "ts-essentials"
3
- import { Maybe, IResponseListener, Endpoint } from "../dist"
4
-
5
- // Scalars
6
- export type IDate = string | Date
7
- export declare type ISODate = IDate
8
-
9
- // Enums
10
-
11
- export declare enum BookType {
12
- dolor = "DOLOR",
13
- ipsum = "IPSUM",
14
- sit = "SIT",
15
- }
16
-
17
- type AllEnums = BookType
18
-
19
- // Args
20
- export interface BooksWithoutParamsArgs {}
21
- export interface BooksWithOptionalParamsArgs {
22
- params?: BookSearchParamsAllOptional
23
- }
24
- export interface BooksWithRequiredParamsArgs {
25
- params: BookSearchParamsSomeRequired
26
- }
27
- export interface FailingQueryArgs {
28
- id: string
29
- }
30
-
31
- // Input/Output Types
32
-
33
- /**
34
- * @deprecated Avoid directly using this interface. Instead, create a type alias based on the query/mutation return type.
35
- */
36
-
37
- export interface Book {
38
- title?: string
39
- author?: string
40
- type?: BookType
41
- dateCreated?: ISODate
42
- }
43
-
44
- /**
45
- * @deprecated Avoid directly using this interface. Instead, create a type alias based on the query/mutation return type.
46
- */
47
-
48
- export interface BookSearchParamsAllOptional {
49
- title?: string
50
- author?: string
51
- createdAfter?: ISODate
52
- }
53
-
54
- /**
55
- * @deprecated Avoid directly using this interface. Instead, create a type alias based on the query/mutation return type.
56
- */
57
-
58
- export interface BookSearchParamsSomeRequired {
59
- title: string
60
- author?: string
61
- }
62
-
63
- /**
64
- * @deprecated Avoid directly using this interface. Instead, create a type alias based on the query/mutation return type.
65
- */
66
-
67
- export interface Query {
68
- booksWithoutParams?: Book[]
69
- booksWithOptionalParams?: Book[]
70
- booksWithRequiredParams?: Book[]
71
- failingQuery?: string
72
- }
73
-
74
- // Selection Types
75
-
76
- export interface BookSelection {
77
- title?: boolean
78
- author?: boolean
79
- type?: boolean
80
- dateCreated?: boolean
81
- }
82
-
83
- export interface BookSearchParamsAllOptionalSelection {
84
- title?: boolean
85
- author?: boolean
86
- createdAfter?: boolean
87
- }
88
-
89
- export interface BookSearchParamsSomeRequiredSelection {
90
- title?: boolean
91
- author?: boolean
92
- }
93
-
94
- export declare const myApiClient: {
95
- addResponseListener: (listener: IResponseListener) => void
96
- setHeader: (key: string, value: string) => void
97
- setHeaders: (newHeaders: { [k: string]: string }) => void
98
- setUrl: (url: string) => void
99
- setRetryConfig: (options: {
100
- max: number
101
- waitBeforeRetry?: number
102
- before?: IResponseListener
103
- }) => void
104
- queries: {
105
- booksWithoutParams: Endpoint<
106
- {
107
- __headers?: { [key: string]: string }
108
- __retry?: boolean
109
- __alias?: string
110
- } & BookSelection,
111
- DeepRequired<Book[]>,
112
- AllEnums
113
- >
114
- booksWithOptionalParams: Endpoint<
115
- {
116
- __headers?: { [key: string]: string }
117
- __retry?: boolean
118
- __alias?: string
119
- __args?: BooksWithOptionalParamsArgs
120
- } & BookSelection,
121
- DeepRequired<Book[]>,
122
- AllEnums
123
- >
124
- booksWithRequiredParams: Endpoint<
125
- {
126
- __headers?: { [key: string]: string }
127
- __retry?: boolean
128
- __alias?: string
129
- __args: BooksWithRequiredParamsArgs
130
- } & BookSelection,
131
- DeepRequired<Book[]>,
132
- AllEnums
133
- >
134
- failingQuery: Endpoint<
135
- {
136
- __headers?: { [key: string]: string }
137
- __retry?: boolean
138
- __alias?: string
139
- __args: FailingQueryArgs
140
- },
141
- string,
142
- AllEnums
143
- >
144
- }
145
- mutations: {}
146
- }
147
-
148
- export default myApiClient
@@ -1,110 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
- var __export = (target, all) => {
9
- __markAsModule(target);
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __reExport = (target, module2, desc) => {
14
- if (module2 && typeof module2 === "object" || typeof module2 === "function") {
15
- for (let key of __getOwnPropNames(module2))
16
- if (!__hasOwnProp.call(target, key) && key !== "default")
17
- __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
18
- }
19
- return target;
20
- };
21
- var __toModule = (module2) => {
22
- return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
23
- };
24
- __export(exports, {
25
- BookType: () => BookType,
26
- default: () => stdin_default,
27
- myApiClient: () => myApiClient
28
- });
29
- var import_endpoint = __toModule(require("../dist/endpoint"));
30
- var import_standalone = __toModule(require("prettier/standalone"));
31
- var import_parser_graphql = __toModule(require("prettier/parser-graphql"));
32
- const formatGraphQL = (query) => (0, import_standalone.format)(query, { parser: "graphql", plugins: [import_parser_graphql.default] });
33
- const BookType = {
34
- dolor: "DOLOR",
35
- ipsum: "IPSUM",
36
- sit: "SIT"
37
- };
38
- const typesTree = {
39
- Query: {
40
- get booksWithOptionalParams() {
41
- return {
42
- __args: {
43
- params: "BookSearchParamsAllOptional!"
44
- }
45
- };
46
- },
47
- get booksWithRequiredParams() {
48
- return {
49
- __args: {
50
- params: "BookSearchParamsSomeRequired!"
51
- }
52
- };
53
- },
54
- get failingQuery() {
55
- return {
56
- __args: {
57
- id: "String!"
58
- }
59
- };
60
- },
61
- booksWithoutParams: {}
62
- }
63
- };
64
- let verbose = false;
65
- let headers = {};
66
- let url = "http://localhost:4123/graphql";
67
- let retryConfig = {
68
- max: 0,
69
- before: void 0,
70
- waitBeforeRetry: 0
71
- };
72
- let responseListeners = [];
73
- let errorsParser = void 0;
74
- let apiEndpoint = (0, import_endpoint.getApiEndpointCreator)({
75
- getClient: () => ({ url, headers, retryConfig }),
76
- responseListeners,
77
- maxAge: 3e4,
78
- verbose,
79
- typesTree,
80
- formatGraphQL,
81
- errorsParser
82
- });
83
- const myApiClient = {
84
- addResponseListener: (listener) => responseListeners.push(listener),
85
- setHeader: (key, value) => {
86
- headers[key] = value;
87
- },
88
- setHeaders: (newHeaders) => {
89
- headers = newHeaders;
90
- },
91
- setRetryConfig: (options) => {
92
- if (!Number.isInteger(options.max) || options.max < 0) {
93
- throw new Error("retryOptions.max should be a non-negative integer");
94
- }
95
- retryConfig = {
96
- max: options.max,
97
- waitBeforeRetry: options.waitBeforeRetry,
98
- before: options.before
99
- };
100
- },
101
- setUrl: (_url) => url = _url,
102
- queries: {
103
- booksWithoutParams: apiEndpoint("query", "booksWithoutParams"),
104
- booksWithOptionalParams: apiEndpoint("query", "booksWithOptionalParams"),
105
- booksWithRequiredParams: apiEndpoint("query", "booksWithRequiredParams"),
106
- failingQuery: apiEndpoint("query", "failingQuery")
107
- },
108
- mutations: {}
109
- };
110
- var stdin_default = myApiClient;