@constructive-io/graphql-query 2.4.7 → 2.5.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.
@@ -0,0 +1,379 @@
1
+ import { print as gqlPrint } from 'graphql';
2
+ import inflection from 'inflection';
3
+ import { createOne, deleteOne, getAll, getCount, getMany, getOne, patchOne, } from './ast';
4
+ import { validateMetaObject } from './meta-object';
5
+ export * as MetaObject from './meta-object';
6
+ const isObject = (val) => val !== null && typeof val === 'object';
7
+ export class QueryBuilder {
8
+ _introspection;
9
+ _meta;
10
+ _models;
11
+ _model;
12
+ _fields;
13
+ _key;
14
+ _queryName;
15
+ _ast;
16
+ _edges;
17
+ _op;
18
+ _mutation;
19
+ _select;
20
+ constructor({ meta = {}, introspection }) {
21
+ this._introspection = introspection;
22
+ this._meta = meta;
23
+ this.clear();
24
+ this.initModelMap();
25
+ this.pickScalarFields = pickScalarFields.bind(this);
26
+ this.pickAllFields = pickAllFields.bind(this);
27
+ const result = validateMetaObject(this._meta);
28
+ if (typeof result === 'object' && result.errors) {
29
+ throw new Error(`QueryBuilder: meta object is invalid:\n${result.message}`);
30
+ }
31
+ }
32
+ /*
33
+ * Save all gql queries and mutations by model name for quicker lookup
34
+ */
35
+ initModelMap() {
36
+ this._models = Object.keys(this._introspection).reduce((map, key) => {
37
+ const defn = this._introspection[key];
38
+ map = {
39
+ ...map,
40
+ [defn.model]: {
41
+ ...map[defn.model],
42
+ ...{ [key]: defn },
43
+ },
44
+ };
45
+ return map;
46
+ }, {});
47
+ }
48
+ clear() {
49
+ this._model = '';
50
+ this._fields = [];
51
+ this._key = null;
52
+ this._queryName = '';
53
+ this._ast = null;
54
+ this._edges = false;
55
+ this._op = '';
56
+ this._mutation = '';
57
+ this._select = [];
58
+ }
59
+ query(model) {
60
+ this.clear();
61
+ this._model = model;
62
+ return this;
63
+ }
64
+ _findQuery() {
65
+ // based on the op, finds the relevant GQL query
66
+ const queries = this._models[this._model];
67
+ if (!queries) {
68
+ throw new Error('No queries found for ' + this._model);
69
+ }
70
+ const matchQuery = Object.entries(queries).find(([_, defn]) => defn.qtype === this._op);
71
+ if (!matchQuery) {
72
+ throw new Error('No query found for ' + this._model + ':' + this._op);
73
+ }
74
+ const queryKey = matchQuery[0];
75
+ return queryKey;
76
+ }
77
+ _findMutation() {
78
+ // For mutation, there can be many defns that match the operation being requested
79
+ // .ie: deleteAction, deleteActionBySlug, deleteActionByName
80
+ const matchingDefns = Object.keys(this._introspection).reduce((arr, mutationKey) => {
81
+ const defn = this._introspection[mutationKey];
82
+ if (defn.model === this._model &&
83
+ defn.qtype === this._op &&
84
+ defn.qtype === 'mutation' &&
85
+ defn.mutationType === this._mutation) {
86
+ arr = [...arr, { defn, mutationKey }];
87
+ }
88
+ return arr;
89
+ }, []);
90
+ if (matchingDefns.length === 0) {
91
+ throw new Error('no mutation found for ' + this._model + ':' + this._mutation);
92
+ }
93
+ // We only need deleteAction from all of [deleteAction, deleteActionBySlug, deleteActionByName]
94
+ const getInputName = (mutationType) => {
95
+ switch (mutationType) {
96
+ case 'delete': {
97
+ return `Delete${inflection.camelize(this._model)}Input`;
98
+ }
99
+ case 'create': {
100
+ return `Create${inflection.camelize(this._model)}Input`;
101
+ }
102
+ case 'patch': {
103
+ return `Update${inflection.camelize(this._model)}Input`;
104
+ }
105
+ default:
106
+ throw new Error('Unhandled mutation type' + mutationType);
107
+ }
108
+ };
109
+ const matchDefn = matchingDefns.find(({ defn }) => defn.properties.input.type === getInputName(this._mutation));
110
+ if (!matchDefn) {
111
+ throw new Error('no mutation found for ' + this._model + ':' + this._mutation);
112
+ }
113
+ return matchDefn.mutationKey;
114
+ }
115
+ select(selection) {
116
+ const defn = this._introspection[this._key];
117
+ // If selection not given, pick only scalar fields
118
+ if (selection == null) {
119
+ this._select = this.pickScalarFields(null, defn);
120
+ return this;
121
+ }
122
+ this._select = this.pickAllFields(selection, defn);
123
+ return this;
124
+ }
125
+ edges(useEdges) {
126
+ this._edges = useEdges;
127
+ return this;
128
+ }
129
+ getMany({ select } = {}) {
130
+ this._op = 'getMany';
131
+ this._key = this._findQuery();
132
+ this.queryName(inflection.camelize(['get', inflection.underscore(this._key), 'query'].join('_'), true));
133
+ const defn = this._introspection[this._key];
134
+ this.select(select);
135
+ this._ast = getMany({
136
+ builder: this,
137
+ queryName: this._queryName,
138
+ operationName: this._key,
139
+ query: defn,
140
+ selection: this._select,
141
+ });
142
+ return this;
143
+ }
144
+ all({ select } = {}) {
145
+ this._op = 'getMany';
146
+ this._key = this._findQuery();
147
+ this.queryName(inflection.camelize(['get', inflection.underscore(this._key), 'query', 'all'].join('_'), true));
148
+ const defn = this._introspection[this._key];
149
+ this.select(select);
150
+ this._ast = getAll({
151
+ queryName: this._queryName,
152
+ operationName: this._key,
153
+ query: defn,
154
+ selection: this._select,
155
+ });
156
+ return this;
157
+ }
158
+ count() {
159
+ this._op = 'getMany';
160
+ this._key = this._findQuery();
161
+ this.queryName(inflection.camelize(['get', inflection.underscore(this._key), 'count', 'query'].join('_'), true));
162
+ const defn = this._introspection[this._key];
163
+ this._ast = getCount({
164
+ queryName: this._queryName,
165
+ operationName: this._key,
166
+ query: defn,
167
+ });
168
+ return this;
169
+ }
170
+ getOne({ select } = {}) {
171
+ this._op = 'getOne';
172
+ this._key = this._findQuery();
173
+ this.queryName(inflection.camelize(['get', inflection.underscore(this._key), 'query'].join('_'), true));
174
+ const defn = this._introspection[this._key];
175
+ this.select(select);
176
+ this._ast = getOne({
177
+ builder: this,
178
+ queryName: this._queryName,
179
+ operationName: this._key,
180
+ query: defn,
181
+ selection: this._select,
182
+ });
183
+ return this;
184
+ }
185
+ create({ select } = {}) {
186
+ this._op = 'mutation';
187
+ this._mutation = 'create';
188
+ this._key = this._findMutation();
189
+ this.queryName(inflection.camelize([inflection.underscore(this._key), 'mutation'].join('_'), true));
190
+ const defn = this._introspection[this._key];
191
+ this.select(select);
192
+ this._ast = createOne({
193
+ operationName: this._key,
194
+ mutationName: this._queryName,
195
+ mutation: defn,
196
+ selection: this._select,
197
+ });
198
+ return this;
199
+ }
200
+ delete({ select } = {}) {
201
+ this._op = 'mutation';
202
+ this._mutation = 'delete';
203
+ this._key = this._findMutation();
204
+ this.queryName(inflection.camelize([inflection.underscore(this._key), 'mutation'].join('_'), true));
205
+ const defn = this._introspection[this._key];
206
+ this.select(select);
207
+ this._ast = deleteOne({
208
+ operationName: this._key,
209
+ mutationName: this._queryName,
210
+ mutation: defn,
211
+ });
212
+ return this;
213
+ }
214
+ update({ select } = {}) {
215
+ this._op = 'mutation';
216
+ this._mutation = 'patch';
217
+ this._key = this._findMutation();
218
+ this.queryName(inflection.camelize([inflection.underscore(this._key), 'mutation'].join('_'), true));
219
+ const defn = this._introspection[this._key];
220
+ this.select(select);
221
+ this._ast = patchOne({
222
+ operationName: this._key,
223
+ mutationName: this._queryName,
224
+ mutation: defn,
225
+ selection: this._select,
226
+ });
227
+ return this;
228
+ }
229
+ queryName(name) {
230
+ this._queryName = name;
231
+ return this;
232
+ }
233
+ print() {
234
+ if (!this._ast) {
235
+ throw new Error('No AST generated. Please call a query method first.');
236
+ }
237
+ const _hash = gqlPrint(this._ast);
238
+ return {
239
+ _hash,
240
+ _queryName: this._queryName,
241
+ _ast: this._ast,
242
+ };
243
+ }
244
+ // Bind methods that will be called with different this context
245
+ pickScalarFields;
246
+ pickAllFields;
247
+ }
248
+ /**
249
+ * Pick scalar fields of a query definition
250
+ * @param {Object} defn Query definition
251
+ * @param {Object} meta Meta object containing info about table relations
252
+ * @returns {Array}
253
+ */
254
+ function pickScalarFields(selection, defn) {
255
+ const model = defn.model;
256
+ const modelMeta = this._meta.tables.find((t) => t.name === model);
257
+ if (!modelMeta) {
258
+ throw new Error(`Model meta not found for ${model}`);
259
+ }
260
+ const isInTableSchema = (fieldName) => !!modelMeta.fields.find((field) => field.name === fieldName);
261
+ const pickFrom = (modelSelection) => modelSelection
262
+ .filter((fieldName) => {
263
+ // If not specified or not a valid selection list, allow all
264
+ if (selection == null || !Array.isArray(selection))
265
+ return true;
266
+ return Object.keys(selection).includes(fieldName);
267
+ })
268
+ .filter((fieldName) => !isRelationalField(fieldName, modelMeta) && isInTableSchema(fieldName))
269
+ .map((fieldName) => ({
270
+ name: fieldName,
271
+ isObject: false,
272
+ fieldDefn: modelMeta.fields.find((f) => f.name === fieldName),
273
+ }));
274
+ // This is for inferring the sub-selection of a mutation query
275
+ // from a definition model .eg UserSetting, find its related queries in the introspection object, and pick its selection fields
276
+ if (defn.qtype === 'mutation') {
277
+ const relatedQuery = this._introspection[`${modelNameToGetMany(defn.model)}`];
278
+ return pickFrom(relatedQuery.selection);
279
+ }
280
+ return pickFrom(defn.selection);
281
+ }
282
+ /**
283
+ * Pick scalar fields and sub-selection fields of a query definition
284
+ * @param {Object} selection Selection clause object
285
+ * @param {Object} defn Query definition
286
+ * @param {Object} meta Meta object containing info about table relations
287
+ * @returns {Array}
288
+ */
289
+ function pickAllFields(selection, defn) {
290
+ const model = defn.model;
291
+ const modelMeta = this._meta.tables.find((t) => t.name === model);
292
+ if (!modelMeta) {
293
+ throw new Error(`Model meta not found for ${model}`);
294
+ }
295
+ const selectionEntries = Object.entries(selection);
296
+ let fields = [];
297
+ const isWhiteListed = (selectValue) => {
298
+ return typeof selectValue === 'boolean' && selectValue;
299
+ };
300
+ for (const entry of selectionEntries) {
301
+ const [fieldName, fieldOptions] = entry;
302
+ // Case
303
+ // {
304
+ // goalResults: // fieldName
305
+ // { select: { id: true }, variables: { first: 100 } } // fieldOptions
306
+ // }
307
+ if (isObject(fieldOptions)) {
308
+ if (!isFieldInDefinition(fieldName, defn, modelMeta)) {
309
+ continue;
310
+ }
311
+ const referencedForeignConstraint = modelMeta.foreignConstraints.find((constraint) => constraint.fromKey.name === fieldName ||
312
+ constraint.fromKey.alias === fieldName);
313
+ const subFields = Object.keys(fieldOptions.select).filter((subField) => {
314
+ return (!isRelationalField(subField, modelMeta) &&
315
+ isWhiteListed(fieldOptions.select[subField]));
316
+ });
317
+ const isBelongTo = !!referencedForeignConstraint;
318
+ const fieldSelection = {
319
+ name: fieldName,
320
+ isObject: true,
321
+ isBelongTo,
322
+ selection: subFields.map((name) => ({ name, isObject: false })),
323
+ variables: fieldOptions.variables,
324
+ };
325
+ // Need to further expand selection of object fields,
326
+ // but only non-graphql-builtin, non-relation fields
327
+ // .ie action { id location }
328
+ // location is non-scalar and non-relational, thus need to further expand into { x y ... }
329
+ if (isBelongTo) {
330
+ const getManyName = modelNameToGetMany(referencedForeignConstraint.refTable);
331
+ const refDefn = this._introspection[getManyName];
332
+ fieldSelection.selection = pickScalarFields.call(this, { [fieldName]: true }, refDefn);
333
+ }
334
+ fields = [...fields, fieldSelection];
335
+ }
336
+ else {
337
+ // Case
338
+ // {
339
+ // userId: true // [fieldName, fieldOptions]
340
+ // }
341
+ if (isWhiteListed(fieldOptions)) {
342
+ fields = [
343
+ ...fields,
344
+ {
345
+ name: fieldName,
346
+ isObject: false,
347
+ fieldDefn: modelMeta.fields.find((f) => f.name === fieldName),
348
+ },
349
+ ];
350
+ }
351
+ }
352
+ }
353
+ return fields;
354
+ }
355
+ function isFieldInDefinition(fieldName, defn, modelMeta) {
356
+ const isReferenced = !!modelMeta.foreignConstraints.find((constraint) => constraint.fromKey.name === fieldName ||
357
+ constraint.fromKey.alias === fieldName);
358
+ return (isReferenced ||
359
+ defn.selection.some((selectionItem) => {
360
+ if (typeof selectionItem === 'string') {
361
+ return fieldName === selectionItem;
362
+ }
363
+ if (isObject(selectionItem)) {
364
+ return selectionItem.name === fieldName;
365
+ }
366
+ return false;
367
+ }));
368
+ }
369
+ // TODO: see if there is a possibility of supertyping table (a key is both a foreign and primary key)
370
+ // A relational field is a foreign key but not a primary key
371
+ function isRelationalField(fieldName, modelMeta) {
372
+ return (!modelMeta.primaryConstraints.find((field) => field.name === fieldName) &&
373
+ !!modelMeta.foreignConstraints.find((constraint) => constraint.fromKey.name === fieldName));
374
+ }
375
+ // Get getMany op name from model
376
+ // ie. UserSetting => userSettings
377
+ function modelNameToGetMany(model) {
378
+ return inflection.camelize(inflection.pluralize(inflection.underscore(model)), true);
379
+ }
package/esm/types.js ADDED
@@ -0,0 +1,24 @@
1
+ // Type guards for runtime validation
2
+ export function isGraphQLVariableValue(value) {
3
+ return (value === null ||
4
+ typeof value === 'string' ||
5
+ typeof value === 'number' ||
6
+ typeof value === 'boolean');
7
+ }
8
+ export function isGraphQLVariables(obj) {
9
+ if (!obj || typeof obj !== 'object')
10
+ return false;
11
+ for (const [key, value] of Object.entries(obj)) {
12
+ if (typeof key !== 'string')
13
+ return false;
14
+ if (Array.isArray(value)) {
15
+ if (!value.every((item) => isGraphQLVariableValue(item) || isGraphQLVariables(item))) {
16
+ return false;
17
+ }
18
+ }
19
+ else if (!isGraphQLVariableValue(value) && !isGraphQLVariables(value)) {
20
+ return false;
21
+ }
22
+ }
23
+ return true;
24
+ }
package/index.d.ts CHANGED
@@ -1,22 +1,3 @@
1
+ export { QueryBuilder } from './query-builder';
2
+ export * from './types';
1
3
  export * as MetaObject from './meta-object';
2
- export declare class QueryBuilder {
3
- constructor({ meta, introspection }: {
4
- meta?: {};
5
- introspection: any;
6
- });
7
- initModelMap(): void;
8
- clear(): void;
9
- query(model: any): this;
10
- _findQuery(): string;
11
- _findMutation(): any;
12
- select(selection: any): this;
13
- edges(useEdges: any): this;
14
- getMany({ select }?: {}): this;
15
- all({ select }?: {}): this;
16
- getOne({ select }?: {}): this;
17
- create({ select }?: {}): this;
18
- delete({ select }?: {}): this;
19
- update({ select }?: {}): this;
20
- queryName(name: any): this;
21
- print(): this;
22
- }