-
Notifications
You must be signed in to change notification settings - Fork 32
/
PgConnectionArgFilterPlugin.ts
536 lines (497 loc) · 16.2 KB
/
PgConnectionArgFilterPlugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import type { Context, Plugin } from "graphile-build";
import type {
PgClass,
PgProc,
PgType,
QueryBuilder,
SQL,
} from "graphile-build-pg";
import type {
GraphQLInputFieldConfigMap,
GraphQLInputType,
GraphQLType,
} from "graphql";
import { BackwardRelationSpec } from "./PgConnectionArgFilterBackwardRelationsPlugin";
const PgConnectionArgFilterPlugin: Plugin = (
builder,
{
connectionFilterAllowedFieldTypes,
connectionFilterArrays,
connectionFilterSetofFunctions,
connectionFilterAllowNullInput,
connectionFilterAllowEmptyObjectInput,
}
) => {
// Add `filter` input argument to connection and simple collection types
builder.hook(
"GraphQLObjectType:fields:field:args",
(args, build, context) => {
const {
extend,
newWithHooks,
getTypeByName,
inflection,
pgGetGqlTypeByTypeIdAndModifier,
pgOmit: omit,
connectionFilterResolve,
connectionFilterType,
} = build;
const {
scope: {
isPgFieldConnection,
isPgFieldSimpleCollection,
pgFieldIntrospection: source,
},
addArgDataGenerator,
field,
Self,
} = context as Context<GraphQLInputFieldConfigMap> & {
scope: {
pgFieldIntrospection: PgClass | PgProc;
isPgConnectionFilter?: boolean;
};
};
const shouldAddFilter = isPgFieldConnection || isPgFieldSimpleCollection;
if (!shouldAddFilter) return args;
if (!source) return args;
if (omit(source, "filter")) return args;
if (source.kind === "procedure") {
if (!(source.tags.filterable || connectionFilterSetofFunctions)) {
return args;
}
}
const returnTypeId =
source.kind === "class" ? source.type.id : source.returnTypeId;
const returnType =
source.kind === "class"
? source.type
: (build.pgIntrospectionResultsByKind.type as PgType[]).find(
(t) => t.id === returnTypeId
);
if (!returnType) {
return args;
}
const isRecordLike = returnTypeId === "2249";
const nodeTypeName = isRecordLike
? inflection.recordFunctionReturnType(source)
: pgGetGqlTypeByTypeIdAndModifier(returnTypeId, null).name;
const filterTypeName = inflection.filterType(nodeTypeName);
const nodeType = getTypeByName(nodeTypeName);
if (!nodeType) {
return args;
}
const nodeSource =
source.kind === "procedure" && returnType.class
? returnType.class
: source;
const FilterType = connectionFilterType(
newWithHooks,
filterTypeName,
nodeSource,
nodeTypeName
);
if (!FilterType) {
return args;
}
// Generate SQL where clause from filter argument
addArgDataGenerator(function connectionFilter(args: any) {
return {
pgQuery: (queryBuilder: QueryBuilder) => {
if (Object.prototype.hasOwnProperty.call(args, "filter")) {
const sqlFragment = connectionFilterResolve(
args.filter,
queryBuilder.getTableAlias(),
filterTypeName,
queryBuilder,
returnType,
null
);
if (sqlFragment != null) {
queryBuilder.where(sqlFragment);
}
}
},
};
});
return extend(
args,
{
filter: {
description:
"A filter to be used in determining which values should be returned by the collection.",
type: FilterType,
},
},
`Adding connection filter arg to field '${field.name}' of '${Self.name}'`
);
}
);
builder.hook("build", (build) => {
const {
extend,
graphql: { getNamedType, GraphQLInputObjectType, GraphQLList },
inflection,
pgIntrospectionResultsByKind: introspectionResultsByKind,
pgGetGqlInputTypeByTypeIdAndModifier,
pgGetGqlTypeByTypeIdAndModifier,
pgSql: sql,
} = build;
const connectionFilterResolvers: { [typeName: string]: any } = {};
const connectionFilterTypesByTypeName: {
[typeName: string]: any;
} = {};
const handleNullInput = () => {
if (!connectionFilterAllowNullInput) {
throw new Error(
"Null literals are forbidden in filter argument input."
);
}
return null;
};
const handleEmptyObjectInput = () => {
if (!connectionFilterAllowEmptyObjectInput) {
throw new Error(
"Empty objects are forbidden in filter argument input."
);
}
return null;
};
const isEmptyObject = (obj: any) =>
typeof obj === "object" &&
obj !== null &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0;
const connectionFilterRegisterResolver = (
typeName: string,
fieldName: string,
resolve: any
) => {
connectionFilterResolvers[typeName] = extend(
connectionFilterResolvers[typeName] || {},
{ [fieldName]: resolve }
);
};
const connectionFilterResolve = (
obj: any,
sourceAlias: SQL,
typeName: string,
queryBuilder: QueryBuilder,
pgType: PgType,
pgTypeModifier: number,
parentFieldName: string,
parentFieldInfo: { backwardRelationSpec: BackwardRelationSpec }
) => {
if (obj == null) return handleNullInput();
if (isEmptyObject(obj)) return handleEmptyObjectInput();
const sqlFragments = Object.entries(obj)
.map(([key, value]) => {
if (value == null) return handleNullInput();
if (isEmptyObject(value)) return handleEmptyObjectInput();
const resolversByFieldName = connectionFilterResolvers[typeName];
if (resolversByFieldName && resolversByFieldName[key]) {
return resolversByFieldName[key]({
sourceAlias,
fieldName: key,
fieldValue: value,
queryBuilder,
pgType,
pgTypeModifier,
parentFieldName,
parentFieldInfo,
});
}
throw new Error(`Unable to resolve filter field '${key}'`);
})
.filter((x) => x != null);
return sqlFragments.length === 0
? null
: sql.query`(${sql.join(sqlFragments, ") and (")})`;
};
// Get or create types like IntFilter, StringFilter, etc.
const connectionFilterOperatorsType = (
newWithHooks: any,
pgTypeId: number,
pgTypeModifier: number
) => {
const pgType = introspectionResultsByKind.typeById[pgTypeId];
const allowedPgTypeTypes = ["b", "d", "e", "r"];
if (!allowedPgTypeTypes.includes(pgType.type)) {
// Not a base, domain, enum, or range type? Skip.
return null;
}
// Perform some checks on the simple type (after removing array/range/domain wrappers)
const pgGetNonArrayType = (pgType: PgType) =>
pgType.isPgArray && pgType.arrayItemType
? pgType.arrayItemType
: pgType;
const pgGetNonRangeType = (pgType: PgType) =>
(pgType as any).rangeSubTypeId
? introspectionResultsByKind.typeById[(pgType as any).rangeSubTypeId]
: pgType;
const pgGetNonDomainType = (pgType: PgType) =>
pgType.type === "d" && pgType.domainBaseTypeId
? introspectionResultsByKind.typeById[pgType.domainBaseTypeId]
: pgType;
const pgGetSimpleType = (pgType: PgType) =>
pgGetNonDomainType(pgGetNonRangeType(pgGetNonArrayType(pgType)));
const pgSimpleType = pgGetSimpleType(pgType);
if (!pgSimpleType) return null;
if (
!(
pgSimpleType.type === "e" ||
(pgSimpleType.type === "b" && !pgSimpleType.isPgArray)
)
) {
// Haven't found an enum type or a non-array base type? Skip.
return null;
}
if (pgSimpleType.name === "json") {
// The PG `json` type has no valid operators.
// Skip filter type creation to allow the proper
// operators to be exposed for PG `jsonb` types.
return null;
}
// Establish field type and field input type
const fieldType: GraphQLType | undefined =
pgGetGqlTypeByTypeIdAndModifier(pgTypeId, pgTypeModifier);
if (!fieldType) return null;
const fieldInputType: GraphQLType | undefined =
pgGetGqlInputTypeByTypeIdAndModifier(pgTypeId, pgTypeModifier);
if (!fieldInputType) return null;
// Avoid exposing filter operators on unrecognized types that PostGraphile handles as Strings
const namedType = getNamedType(fieldType);
const namedInputType = getNamedType(fieldInputType);
const actualStringPgTypeIds = [
"1042", // bpchar
"18", // char
"19", // name
"25", // text
"1043", // varchar
];
// Include citext as recognized String type
const citextPgType = (introspectionResultsByKind.type as PgType[]).find(
(t) => t.name === "citext"
);
if (citextPgType) {
actualStringPgTypeIds.push(citextPgType.id);
}
if (
namedInputType &&
namedInputType.name === "String" &&
!actualStringPgTypeIds.includes(pgSimpleType.id)
) {
// Not a real string type? Skip.
return null;
}
// Respect `connectionFilterAllowedFieldTypes` config option
if (
connectionFilterAllowedFieldTypes &&
!connectionFilterAllowedFieldTypes.includes(namedType.name)
) {
return null;
}
const pgConnectionFilterOperatorsCategory = pgType.isPgArray
? "Array"
: pgType.rangeSubTypeId
? "Range"
: pgType.type === "e"
? "Enum"
: pgType.type === "d"
? "Domain"
: "Scalar";
// Respect `connectionFilterArrays` config option
if (
pgConnectionFilterOperatorsCategory === "Array" &&
!connectionFilterArrays
) {
return null;
}
const rangeElementInputType = pgType.rangeSubTypeId
? pgGetGqlInputTypeByTypeIdAndModifier(
pgType.rangeSubTypeId,
pgTypeModifier
)
: null;
const domainBaseType =
pgType.type === "d"
? pgGetGqlTypeByTypeIdAndModifier(
pgType.domainBaseTypeId,
pgType.domainTypeModifier
)
: null;
const isListType = fieldType instanceof GraphQLList;
const operatorsTypeName = isListType
? inflection.filterFieldListType(namedType.name)
: inflection.filterFieldType(namedType.name);
const existingType = connectionFilterTypesByTypeName[operatorsTypeName];
if (existingType) {
if (
typeof existingType._fields === "object" &&
Object.keys(existingType._fields).length === 0
) {
// Existing type is fully defined and
// there are no fields, so don't return a type
return null;
}
// Existing type isn't fully defined or is
// fully defined with fields, so return it
return existingType;
}
return newWithHooks(
GraphQLInputObjectType,
{
name: operatorsTypeName,
description: `A filter to be used against ${namedType.name}${
isListType ? " List" : ""
} fields. All fields are combined with a logical ‘and.’`,
},
{
isPgConnectionFilterOperators: true,
pgConnectionFilterOperatorsCategory,
fieldType,
fieldInputType,
rangeElementInputType,
domainBaseType,
},
true
);
};
const connectionFilterType = (
newWithHooks: any,
filterTypeName: string,
source: PgClass | PgProc,
nodeTypeName: string
) => {
const existingType = connectionFilterTypesByTypeName[filterTypeName];
if (existingType) {
if (
typeof existingType._fields === "object" &&
Object.keys(existingType._fields).length === 0
) {
// Existing type is fully defined and
// there are no fields, so don't return a type
return null;
}
// Existing type isn't fully defined or is
// fully defined with fields, so return it
return existingType;
}
return newWithHooks(
GraphQLInputObjectType,
{
description: `A filter to be used against \`${nodeTypeName}\` object types. All fields are combined with a logical ‘and.’`,
name: filterTypeName,
},
{
pgIntrospection: source,
isPgConnectionFilter: true,
},
true
);
};
const escapeLikeWildcards = (input: string) => {
if ("string" !== typeof input) {
throw new Error("Non-string input was provided to escapeLikeWildcards");
} else {
return input.split("%").join("\\%").split("_").join("\\_");
}
};
const addConnectionFilterOperator: AddConnectionFilterOperator = (
typeNames,
operatorName,
description,
resolveType,
resolve,
options = {}
) => {
if (!typeNames) {
const msg = `Missing first argument 'typeNames' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
if (!operatorName) {
const msg = `Missing second argument 'operatorName' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
if (!resolveType) {
const msg = `Missing fourth argument 'resolveType' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
if (!resolve) {
const msg = `Missing fifth argument 'resolve' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
const { connectionFilterScalarOperators } = build;
const gqlTypeNames = Array.isArray(typeNames) ? typeNames : [typeNames];
for (const gqlTypeName of gqlTypeNames) {
if (!connectionFilterScalarOperators[gqlTypeName]) {
connectionFilterScalarOperators[gqlTypeName] = {};
}
if (connectionFilterScalarOperators[gqlTypeName][operatorName]) {
const msg = `Operator '${operatorName}' already exists for type '${gqlTypeName}'.`;
throw new Error(msg);
}
connectionFilterScalarOperators[gqlTypeName][operatorName] = {
description,
resolveType,
resolve,
// These functions may exist on `options`: resolveSqlIdentifier, resolveSqlValue, resolveInput
...options,
};
}
};
return extend(build, {
connectionFilterTypesByTypeName,
connectionFilterRegisterResolver,
connectionFilterResolve,
connectionFilterOperatorsType,
connectionFilterType,
escapeLikeWildcards,
addConnectionFilterOperator,
});
});
};
export interface ConnectionFilterResolver {
(input: {
sourceAlias: SQL;
fieldName: string;
fieldValue?: unknown;
queryBuilder: QueryBuilder;
pgType: PgType;
pgTypeModifier: number | null;
parentFieldName: string;
parentFieldInfo?: { backwardRelationSpec?: BackwardRelationSpec };
}): SQL | null;
}
export interface AddConnectionFilterOperator {
(
typeNames: string | string[],
operatorName: string,
description: string | null,
resolveType: (
fieldInputType: GraphQLInputType,
rangeElementInputType: GraphQLInputType
) => GraphQLType,
resolve: (
sqlIdentifier: SQL,
sqlValue: SQL,
input: unknown,
parentFieldName: string,
queryBuilder: QueryBuilder
) => SQL | null,
options?: {
resolveInput?: (input: unknown) => unknown;
resolveSqlIdentifier?: (
sqlIdentifier: SQL,
pgType: PgType,
pgTypeModifier: number | null
) => SQL;
resolveSqlValue?: (
input: unknown,
pgType: PgType,
pgTypeModifier: number | null,
resolveListItemSqlValue?: any
) => SQL | null;
}
): void;
}
export default PgConnectionArgFilterPlugin;