graphql-query-merger 1.0.1 → 1.0.3

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 ADDED
@@ -0,0 +1,231 @@
1
+ # GraphQL Query Merger
2
+
3
+ **GraphQL Query Merger** is a utility library designed to merge multiple GraphQL queries into a single, cohesive query. This helps developers streamline their GraphQL requests by combining related operations efficiently, avoiding redundancy and improving maintainability.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ - [GraphQL Query Merger](#graphql-query-merger)
10
+ - [Table of Contents](#table-of-contents)
11
+ - [Features](#features)
12
+ - [Installation](#installation)
13
+ - [Usage](#usage)
14
+ - [Importing the Library](#importing-the-library)
15
+ - [Combining Queries](#combining-queries)
16
+ - [Basic Query Combination](#basic-query-combination)
17
+ - [Combining Queries with Variables](#combining-queries-with-variables)
18
+ - [Conditional Query Combination](#conditional-query-combination)
19
+ - [Notes](#notes)
20
+
21
+ ---
22
+
23
+ ## Features
24
+
25
+ - **Merge GraphQL Queries**: Seamlessly combine multiple queries into one.
26
+ - **Variable Deduplication**: Automatically handles conflicts by renaming variables.
27
+ - **Supports Conditional Queries**: Add queries dynamically based on runtime logic.
28
+ - **Customizable Query Names**: Optionally name the resulting query.
29
+
30
+ ---
31
+
32
+ ## Installation
33
+
34
+ To install the library, use npm or yarn:
35
+
36
+ ```bash
37
+ npm install graphql-query-merger graphql
38
+ ```
39
+
40
+ > **Note**: `graphql-query-merger` has a peer dependency on `graphql`. Ensure that the `graphql` package is installed alongside it.
41
+
42
+ ---
43
+
44
+ ## Usage
45
+
46
+ ### Importing the Library
47
+
48
+ To use the library, import the necessary functions:
49
+
50
+ ```javascript
51
+ const { mergeQueries } = require('graphql-query-merger');
52
+ const { print } = require('graphql');
53
+ const { gql } = require('graphql-tag');
54
+ ```
55
+
56
+ - **`mergeQueries()`**: Initializes a new query merger instance.
57
+ - **`push(query, variables?)`**: Adds a query to the merger. Optionally accepts a variables object.
58
+ - **`print()`**: Converts the resulting query to a printable string format.
59
+
60
+ ### Combining Queries
61
+
62
+ #### Basic Query Combination
63
+
64
+ You can combine queries written as strings or `gql`-tagged templates.
65
+
66
+ ```javascript
67
+ const query_1 = /* GraphQL */ `
68
+ {
69
+ user {
70
+ id
71
+ name
72
+ }
73
+ }
74
+ `;
75
+
76
+ const query_2 = /* GraphQL */ gql`
77
+ {
78
+ post {
79
+ id
80
+ title
81
+ }
82
+ }
83
+ `;
84
+
85
+ const combined = mergeQueries().push(query_1).push(query_2);
86
+
87
+ console.log(print(combined.query));
88
+ ```
89
+
90
+ **Output**:
91
+
92
+ ```graphql
93
+ {
94
+ user {
95
+ id
96
+ name
97
+ }
98
+ post {
99
+ id
100
+ title
101
+ }
102
+ }
103
+ ```
104
+
105
+ #### Combining Queries with Variables
106
+
107
+ When combining queries that include variables, the library automatically renames conflicting variable names to maintain uniqueness.
108
+
109
+ ```javascript
110
+ const query_1 = /* GraphQL */ gql`
111
+ query ($id: ID!) {
112
+ user(id: $id) {
113
+ id
114
+ name
115
+ }
116
+ }
117
+ `;
118
+
119
+ const query_2 = /* GraphQL */ `
120
+ query ($id: ID!) {
121
+ post(id: $id) {
122
+ id
123
+ title
124
+ }
125
+ }
126
+ `;
127
+
128
+ const combined = mergeQueries().push(query_1, { id: 1 }).push(query_2, { id: 2 });
129
+
130
+ console.log(print(combined.query));
131
+ console.log(combined.variables);
132
+ ```
133
+
134
+ **Output**:
135
+
136
+ ```graphql
137
+ query ($id_1: ID!, $id_2: ID!) {
138
+ user(id: $id_1) {
139
+ id
140
+ name
141
+ }
142
+ post(id: $id_2) {
143
+ id
144
+ title
145
+ }
146
+ }
147
+ ```
148
+
149
+ **Variables**:
150
+
151
+ ```json
152
+ {
153
+ "id_1": 1,
154
+ "id_2": 2
155
+ }
156
+ ```
157
+
158
+ - **Automatic Variable Renaming**: Conflicting variable names (`id`) are renamed (`id_1`, `id_2`).
159
+
160
+ #### Conditional Query Combination
161
+
162
+ You can dynamically add queries based on runtime conditions.
163
+
164
+ ```javascript
165
+ const combined = mergeQueries('optionalQueryName');
166
+
167
+ combined.push(
168
+ /* GraphQL */ `
169
+ query ($email: String!) {
170
+ user(email: $email) {
171
+ id
172
+ name
173
+ }
174
+ }
175
+ `,
176
+ { email: 'example@test.com' },
177
+ );
178
+
179
+ if (true) {
180
+ combined.push(
181
+ /* GraphQL */ `
182
+ query ($id: ID!) {
183
+ post(id: $id) {
184
+ id
185
+ title
186
+ date
187
+ }
188
+ }
189
+ `,
190
+ { id: 10 },
191
+ );
192
+ }
193
+
194
+ console.log(print(combined.query));
195
+ console.log(combined.variables);
196
+ ```
197
+
198
+ **Output**:
199
+
200
+ ```graphql
201
+ query optionalQueryName($email_1: String!, $id_2: ID!) {
202
+ user(email: $email_1) {
203
+ id
204
+ name
205
+ }
206
+ post(id: $id_2) {
207
+ id
208
+ title
209
+ date
210
+ }
211
+ }
212
+ ```
213
+
214
+ **Variables**:
215
+
216
+ ```json
217
+ {
218
+ "email_1": "example@test.com",
219
+ "id_2": 10
220
+ }
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Notes
226
+
227
+ 1. **Variable Scope**: The library renames variables in the combined query to ensure no conflicts occur between different queries.
228
+ 2. **Query Formats**: Queries can be provided as:
229
+ - String literals
230
+ - `gql`-tagged templates (recommended for syntax highlighting and validation).
231
+ 3. **Error Handling**: Ensure all variables required by the queries are provided when invoking `push()`. Missing variables will lead to runtime errors.
package/dist/index.es.js CHANGED
@@ -1,143 +1,100 @@
1
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
- var __commonJS = (cb, mod) => function __require() {
3
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4
- };
5
- var require_index_es = __commonJS({
6
- "index.es.js"(exports, module) {
7
- const { Kind, parse, visit } = require("graphql");
8
- function renameVariablesAndFragments(document, variables, uniqueId) {
9
- const variableNameMap = {};
10
- const fragmentNameMap = {};
11
- const newDocument = visit(document, {
12
- [Kind.VARIABLE_DEFINITION](node) {
13
- const oldName = node.variable.name.value;
14
- const newName = `${oldName}_${uniqueId}`;
15
- variableNameMap[oldName] = newName;
16
- return {
17
- ...node,
18
- variable: {
19
- ...node.variable,
20
- name: { kind: Kind.NAME, value: newName }
21
- }
22
- };
23
- },
24
- [Kind.VARIABLE](node) {
25
- const oldName = node.name.value;
26
- const newName = variableNameMap[oldName] || oldName;
27
- return {
28
- ...node,
29
- name: { kind: Kind.NAME, value: newName }
30
- };
31
- },
32
- [Kind.FRAGMENT_DEFINITION](node) {
33
- const oldName = node.name.value;
34
- const newName = `${oldName}_${uniqueId}`;
35
- fragmentNameMap[oldName] = newName;
36
- return {
37
- ...node,
38
- name: { kind: Kind.NAME, value: newName }
39
- };
40
- },
41
- [Kind.FRAGMENT_SPREAD](node) {
42
- const oldName = node.name.value;
43
- const newName = fragmentNameMap[oldName] || oldName;
1
+ import { parse as p, Kind as t, visit as m } from "graphql";
2
+ const d = (c, a, s) => {
3
+ const o = {}, l = {}, r = m(c, {
4
+ [t.VARIABLE_DEFINITION](e) {
5
+ const n = e.variable.name.value, i = `${n}_${s}`;
6
+ return o[n] = i, {
7
+ ...e,
8
+ variable: {
9
+ ...e.variable,
10
+ name: { kind: t.NAME, value: i }
11
+ }
12
+ };
13
+ },
14
+ [t.VARIABLE](e) {
15
+ const n = e.name.value, i = o[n] || n;
16
+ return {
17
+ ...e,
18
+ name: { kind: t.NAME, value: i }
19
+ };
20
+ },
21
+ [t.FRAGMENT_DEFINITION](e) {
22
+ const n = e.name.value, i = `${n}_${s}`;
23
+ return l[n] = i, {
24
+ ...e,
25
+ name: { kind: t.NAME, value: i }
26
+ };
27
+ },
28
+ [t.FRAGMENT_SPREAD](e) {
29
+ const n = e.name.value, i = l[n] || n;
30
+ return {
31
+ ...e,
32
+ name: { kind: t.NAME, value: i }
33
+ };
34
+ },
35
+ [t.DIRECTIVE](e) {
36
+ return m(e, {
37
+ [t.VARIABLE](n) {
38
+ const i = n.name.value, N = o[i] || i;
44
39
  return {
45
- ...node,
46
- name: { kind: Kind.NAME, value: newName }
40
+ ...n,
41
+ name: { kind: t.NAME, value: N }
47
42
  };
48
- },
49
- [Kind.DIRECTIVE](node) {
50
- return visit(node, {
51
- [Kind.VARIABLE](varNode) {
52
- const oldName = varNode.name.value;
53
- const newName = variableNameMap[oldName] || oldName;
54
- return {
55
- ...varNode,
56
- name: { kind: Kind.NAME, value: newName }
57
- };
58
- }
59
- });
60
43
  }
61
44
  });
62
- const newVariables = {};
63
- for (const [key, value] of Object.entries(variables)) {
64
- const newKey = variableNameMap[key] || key;
65
- newVariables[newKey] = value;
66
- }
67
- return { document: newDocument, variables: newVariables };
68
45
  }
69
- class GraphQLQueryMerger {
70
- constructor(operationName) {
71
- this.operationName = operationName;
72
- this.documents = [];
73
- this.internalVariables = [];
74
- this.uniqueIdCounter = 1;
75
- this.operationType = null;
76
- }
77
- push(document, variables = {}) {
78
- if (typeof document === "string") {
79
- document = parse(document);
80
- }
81
- const uniqueId = this.uniqueIdCounter++;
82
- const { document: renamedDocument, variables: renamedVariables } = renameVariablesAndFragments(document, variables, uniqueId);
83
- const operationDefinitions = renamedDocument.definitions.filter(
84
- (def) => def.kind === Kind.OPERATION_DEFINITION
85
- );
86
- if (operationDefinitions.length === 0) {
87
- throw new Error(
88
- "No se encontró una definición de operación en el documento proporcionado."
89
- );
90
- }
91
- const operationType = operationDefinitions[0].operation;
92
- if (this.operationType && this.operationType !== operationType) {
93
- throw new Error(
94
- `No se pueden combinar diferentes tipos de operaciones: ${this.operationType} y ${operationType}.`
95
- );
96
- }
97
- this.operationType = operationType;
98
- this.documents.push(renamedDocument);
99
- this.internalVariables.push(renamedVariables);
100
- return this;
101
- }
102
- get query() {
103
- const allVariableDefinitions = [];
104
- const allSelections = [];
105
- const allFragmentDefinitions = [];
106
- for (const doc of this.documents) {
107
- for (const definition of doc.definitions) {
108
- if (definition.kind === Kind.OPERATION_DEFINITION) {
109
- allVariableDefinitions.push(...definition.variableDefinitions || []);
110
- allSelections.push(...definition.selectionSet.selections);
111
- } else if (definition.kind === Kind.FRAGMENT_DEFINITION) {
112
- allFragmentDefinitions.push(definition);
113
- }
46
+ }), u = {};
47
+ for (const [e, n] of Object.entries(a)) {
48
+ const i = o[e] || e;
49
+ u[i] = n;
50
+ }
51
+ return { document: r, variables: u };
52
+ };
53
+ class E {
54
+ constructor(a) {
55
+ this.operationName = a, this.documents = [], this.internalVariables = [], this.uniqueIdCounter = 1, this.operationType = null;
56
+ }
57
+ push(a, s = {}) {
58
+ typeof a == "string" && (a = p(a));
59
+ const o = this.uniqueIdCounter++, { document: l, variables: r } = d(a, s, o), u = l.definitions.filter(
60
+ (n) => n.kind === t.OPERATION_DEFINITION
61
+ );
62
+ if (u.length === 0)
63
+ throw new Error("No operation definition found in the provided document.");
64
+ const e = u[0].operation;
65
+ if (this.operationType && this.operationType !== e)
66
+ throw new Error(
67
+ `Cannot merge different operation types: ${this.operationType} and ${e}.`
68
+ );
69
+ return this.operationType = e, this.documents.push(l), this.internalVariables.push(r), this;
70
+ }
71
+ get query() {
72
+ const a = [], s = [], o = [];
73
+ for (const l of this.documents)
74
+ for (const r of l.definitions)
75
+ r.kind === t.OPERATION_DEFINITION ? (a.push(...r.variableDefinitions || []), s.push(...r.selectionSet.selections)) : r.kind === t.FRAGMENT_DEFINITION && o.push(r);
76
+ return {
77
+ kind: t.DOCUMENT,
78
+ definitions: [
79
+ {
80
+ kind: t.OPERATION_DEFINITION,
81
+ operation: this.operationType,
82
+ name: { kind: t.NAME, value: this.operationName || "" },
83
+ variableDefinitions: a,
84
+ selectionSet: {
85
+ kind: t.SELECTION_SET,
86
+ selections: s
114
87
  }
115
- }
116
- return {
117
- kind: Kind.DOCUMENT,
118
- definitions: [
119
- {
120
- kind: Kind.OPERATION_DEFINITION,
121
- operation: this.operationType,
122
- name: { kind: Kind.NAME, value: this.operationName || "" },
123
- variableDefinitions: allVariableDefinitions,
124
- selectionSet: {
125
- kind: Kind.SELECTION_SET,
126
- selections: allSelections
127
- }
128
- },
129
- ...allFragmentDefinitions
130
- ]
131
- };
132
- }
133
- get variables() {
134
- return Object.assign({}, ...this.internalVariables);
135
- }
136
- }
137
- function mergeQueries(operationName = "") {
138
- return new GraphQLQueryMerger(operationName);
139
- }
140
- module.exports = { mergeQueries };
88
+ },
89
+ ...o
90
+ ]
91
+ };
92
+ }
93
+ get variables() {
94
+ return Object.assign({}, ...this.internalVariables);
141
95
  }
142
- });
143
- export default require_index_es();
96
+ }
97
+ const f = (c = "") => new E(c);
98
+ export {
99
+ f as mergeQueries
100
+ };
package/dist/index.umd.js CHANGED
@@ -1,139 +1 @@
1
- (function(factory) {
2
- typeof define === "function" && define.amd ? define(factory) : factory();
3
- })(function() {
4
- "use strict";
5
- const { Kind, parse, visit } = require("graphql");
6
- function renameVariablesAndFragments(document, variables, uniqueId) {
7
- const variableNameMap = {};
8
- const fragmentNameMap = {};
9
- const newDocument = visit(document, {
10
- [Kind.VARIABLE_DEFINITION](node) {
11
- const oldName = node.variable.name.value;
12
- const newName = `${oldName}_${uniqueId}`;
13
- variableNameMap[oldName] = newName;
14
- return {
15
- ...node,
16
- variable: {
17
- ...node.variable,
18
- name: { kind: Kind.NAME, value: newName }
19
- }
20
- };
21
- },
22
- [Kind.VARIABLE](node) {
23
- const oldName = node.name.value;
24
- const newName = variableNameMap[oldName] || oldName;
25
- return {
26
- ...node,
27
- name: { kind: Kind.NAME, value: newName }
28
- };
29
- },
30
- [Kind.FRAGMENT_DEFINITION](node) {
31
- const oldName = node.name.value;
32
- const newName = `${oldName}_${uniqueId}`;
33
- fragmentNameMap[oldName] = newName;
34
- return {
35
- ...node,
36
- name: { kind: Kind.NAME, value: newName }
37
- };
38
- },
39
- [Kind.FRAGMENT_SPREAD](node) {
40
- const oldName = node.name.value;
41
- const newName = fragmentNameMap[oldName] || oldName;
42
- return {
43
- ...node,
44
- name: { kind: Kind.NAME, value: newName }
45
- };
46
- },
47
- [Kind.DIRECTIVE](node) {
48
- return visit(node, {
49
- [Kind.VARIABLE](varNode) {
50
- const oldName = varNode.name.value;
51
- const newName = variableNameMap[oldName] || oldName;
52
- return {
53
- ...varNode,
54
- name: { kind: Kind.NAME, value: newName }
55
- };
56
- }
57
- });
58
- }
59
- });
60
- const newVariables = {};
61
- for (const [key, value] of Object.entries(variables)) {
62
- const newKey = variableNameMap[key] || key;
63
- newVariables[newKey] = value;
64
- }
65
- return { document: newDocument, variables: newVariables };
66
- }
67
- class GraphQLQueryMerger {
68
- constructor(operationName) {
69
- this.operationName = operationName;
70
- this.documents = [];
71
- this.internalVariables = [];
72
- this.uniqueIdCounter = 1;
73
- this.operationType = null;
74
- }
75
- push(document, variables = {}) {
76
- if (typeof document === "string") {
77
- document = parse(document);
78
- }
79
- const uniqueId = this.uniqueIdCounter++;
80
- const { document: renamedDocument, variables: renamedVariables } = renameVariablesAndFragments(document, variables, uniqueId);
81
- const operationDefinitions = renamedDocument.definitions.filter(
82
- (def) => def.kind === Kind.OPERATION_DEFINITION
83
- );
84
- if (operationDefinitions.length === 0) {
85
- throw new Error(
86
- "No se encontró una definición de operación en el documento proporcionado."
87
- );
88
- }
89
- const operationType = operationDefinitions[0].operation;
90
- if (this.operationType && this.operationType !== operationType) {
91
- throw new Error(
92
- `No se pueden combinar diferentes tipos de operaciones: ${this.operationType} y ${operationType}.`
93
- );
94
- }
95
- this.operationType = operationType;
96
- this.documents.push(renamedDocument);
97
- this.internalVariables.push(renamedVariables);
98
- return this;
99
- }
100
- get query() {
101
- const allVariableDefinitions = [];
102
- const allSelections = [];
103
- const allFragmentDefinitions = [];
104
- for (const doc of this.documents) {
105
- for (const definition of doc.definitions) {
106
- if (definition.kind === Kind.OPERATION_DEFINITION) {
107
- allVariableDefinitions.push(...definition.variableDefinitions || []);
108
- allSelections.push(...definition.selectionSet.selections);
109
- } else if (definition.kind === Kind.FRAGMENT_DEFINITION) {
110
- allFragmentDefinitions.push(definition);
111
- }
112
- }
113
- }
114
- return {
115
- kind: Kind.DOCUMENT,
116
- definitions: [
117
- {
118
- kind: Kind.OPERATION_DEFINITION,
119
- operation: this.operationType,
120
- name: { kind: Kind.NAME, value: this.operationName || "" },
121
- variableDefinitions: allVariableDefinitions,
122
- selectionSet: {
123
- kind: Kind.SELECTION_SET,
124
- selections: allSelections
125
- }
126
- },
127
- ...allFragmentDefinitions
128
- ]
129
- };
130
- }
131
- get variables() {
132
- return Object.assign({}, ...this.internalVariables);
133
- }
134
- }
135
- function mergeQueries(operationName = "") {
136
- return new GraphQLQueryMerger(operationName);
137
- }
138
- module.exports = { mergeQueries };
139
- });
1
+ (function(r,e){typeof exports=="object"&&typeof module<"u"?e(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],e):(r=typeof globalThis<"u"?globalThis:r||self,e(r["graphql-query-merger"]={},r.graphql))})(this,function(r,e){"use strict";const l=(m,o,d)=>{const s={},u={},a=e.visit(m,{[e.Kind.VARIABLE_DEFINITION](n){const i=n.variable.name.value,t=`${i}_${d}`;return s[i]=t,{...n,variable:{...n.variable,name:{kind:e.Kind.NAME,value:t}}}},[e.Kind.VARIABLE](n){const i=n.name.value,t=s[i]||i;return{...n,name:{kind:e.Kind.NAME,value:t}}},[e.Kind.FRAGMENT_DEFINITION](n){const i=n.name.value,t=`${i}_${d}`;return u[i]=t,{...n,name:{kind:e.Kind.NAME,value:t}}},[e.Kind.FRAGMENT_SPREAD](n){const i=n.name.value,t=u[i]||i;return{...n,name:{kind:e.Kind.NAME,value:t}}},[e.Kind.DIRECTIVE](n){return e.visit(n,{[e.Kind.VARIABLE](i){const t=i.name.value,E=s[t]||t;return{...i,name:{kind:e.Kind.NAME,value:E}}}})}}),c={};for(const[n,i]of Object.entries(o)){const t=s[n]||n;c[t]=i}return{document:a,variables:c}};class N{constructor(o){this.operationName=o,this.documents=[],this.internalVariables=[],this.uniqueIdCounter=1,this.operationType=null}push(o,d={}){typeof o=="string"&&(o=e.parse(o));const s=this.uniqueIdCounter++,{document:u,variables:a}=l(o,d,s),c=u.definitions.filter(i=>i.kind===e.Kind.OPERATION_DEFINITION);if(c.length===0)throw new Error("No operation definition found in the provided document.");const n=c[0].operation;if(this.operationType&&this.operationType!==n)throw new Error(`Cannot merge different operation types: ${this.operationType} and ${n}.`);return this.operationType=n,this.documents.push(u),this.internalVariables.push(a),this}get query(){const o=[],d=[],s=[];for(const u of this.documents)for(const a of u.definitions)a.kind===e.Kind.OPERATION_DEFINITION?(o.push(...a.variableDefinitions||[]),d.push(...a.selectionSet.selections)):a.kind===e.Kind.FRAGMENT_DEFINITION&&s.push(a);return{kind:e.Kind.DOCUMENT,definitions:[{kind:e.Kind.OPERATION_DEFINITION,operation:this.operationType,name:{kind:e.Kind.NAME,value:this.operationName||""},variableDefinitions:o,selectionSet:{kind:e.Kind.SELECTION_SET,selections:d}},...s]}}get variables(){return Object.assign({},...this.internalVariables)}}const f=(m="")=>new N(m);r.mergeQueries=f,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "graphql-query-merger",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Merge and unify multiple GraphQL queries into a single operation with field and variable conflict resolution.",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.es.js",
@@ -17,9 +17,11 @@
17
17
  "query",
18
18
  "merge"
19
19
  ],
20
- "author": "A Juárez",
20
+ "author": "A. Juárez",
21
21
  "license": "ISC",
22
22
  "devDependencies": {
23
+ "@babel/preset-env": "^7.26.0",
24
+ "babel-jest": "^29.7.0",
23
25
  "graphql": "^16.9.0",
24
26
  "graphql-tag": "^2.12.6",
25
27
  "jest": "^29.7.0",